Reputation: 172
I need your help guys with this specific question.
How many numbers from an interval a <= b [1, 10^18] are dividable by 2, 3 or 5?
Result must be run in max 1 sec!
A standard program would use a for loop seen bellow.
a = 1;
b = 1000000000
results = 0;
for (int i = a; i <= b; i++){
if (i % 2 == 0 || i % 3 == 0, i % 5 == 0){
results++;
}
}
System.out.println(results);
But if I enter high numbers, my program need a lot of time to give me the results.
Example 1:
a = 11, b = 30, result = 14
Example 2:
a = 123456789012345678, b = 876543210987654321 , result = 552263376115226339
Upvotes: 0
Views: 139
Reputation: 1608
I came up with something like that
public static void main(String[] args) {
long a = 123456789012345678L, b = 876543210987654321L;
long start = System.currentTimeMillis();
long score = getCount(b) - getCount(a - 1);
System.out.println("Time: " + ((System.currentTimeMillis() - start)));
System.out.println("Divisible by 2 or 3 or 5: " + score);
}
public static long getCount(long end) {
return (end / 2) + (end / 3) + (end / 5) - ((end / 6) + (end / 10) + (end / 15)) + (end / 30);
}
The solution:
Upvotes: 1