Java 8 coding challenge: Count Divisors

Problem:

You have been given 3 integers l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need to print these numbers, you just have to find their count.

Input Format
The first and only line of input contains 3 space separated integers l, r and k.

Output Format
Print the required answer on a single line.

Constraints
1lr10001≤l≤r≤1000
1k10001≤k≤1000

SAMPLE INPUT
1 10 1
SAMPLE OUTPUT
10

Code:

/* IMPORTANT: Multiple classes and nested static classes are supported */
 
/*
 * uncomment this if you want to read input.
//imports for BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
//import for Scanner and other utility classes
import java.util.*;
*/
import java.util.Scanner;
 
class TestClass {
 public static void main(String args[] ) throws Exception {
 Scanner sc = new Scanner(System.in);
 
 int l = sc.nextInt();
 int r = sc.nextInt();
 int k = sc.nextInt();
 
 sc.close();
 int count = 0;
 if(l == r && l%k != 0) {
 System.out.println(0);
 System.exit(0);
 }
 
 while (l <= r) {
 if(l % k == 0) {
 break;
 }
 l++;
 }
 
 count = (r - l) / k + 1;
 System.out.println(count);
 }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s