forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountDivisors.java
35 lines (31 loc) · 1.08 KB
/
CountDivisors.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.rampatra.arrays;
/**
* @author rampatra
* @since 31/05/2016
*/
public class CountDivisors {
/**
* Counts the number of integers in the range {@code begin}
* and {@code end} that are divisible by {@code n}.
*
* @param begin
* @param end
* @param n
* @return
*/
private static int countDivisorsInRange(int begin, int end, int n) {
int b = end / n + 1; // From 0 to end the integers divisible by n
int a = begin / n + 1; // From 0 to begin the integers divisible by n
if (begin % n == 0) { // "begin" is inclusive; if divisible by n then
--a; // remove 1 from "a"
}
return b - a; // return integers in range
}
public static void main(String[] args) {
System.out.println(countDivisorsInRange(0, 0, 5));
System.out.println(countDivisorsInRange(1, 1, 5));
System.out.println(countDivisorsInRange(0, 1, 5));
System.out.println(countDivisorsInRange(0, 10, 5));
System.out.println(countDivisorsInRange(0, 2000000000, 5));
}
}