java - How to find numbers that are dividable with 2, 3 or 5 in max 1 second -
java - How to find numbers that are dividable with 2, 3 or 5 in max 1 second -
i need help guys specific question.
how many numbers interval <= b [1, 10^18] dividable 2, 3 or 5?
result must run in max 1 sec!
a standard programme utilize loop seen bellow.
a = 1; b = 1000000000 results = 0; (int = a; <= b; i++){ if (i % 2 == 0 || % 3 == 0, % 5 == 0){ results++; } } system.out.println(results);
but if come in high numbers, programme need lot of time give me results.
example 1:
a = 11, b = 30, result = 14
example 2:
a = 123456789012345678, b = 876543210987654321 , result = 552263376115226339
i came that
public static void main(string[] args) { long = 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 2 or 3 or 5: " + score); } public static long getcount(long end) { homecoming (end / 2) + (end / 3) + (end / 5) - ((end / 6) + (end / 10) + (end / 15)) + (end / 30); }
the solution:
it counts how many numbers divisible 2 or 3 or 5 separately , sums that. now need discard numbers counted twice: 2 , 3 every 6th number, 2 , 5 every 10th number, 3 , 5 every 15th number at end need include numbers divisible 2 , 3 , 5 discarded in step 2 add together every 30th number. java numbers
Comments
Post a Comment