[英]How to find numbers that are dividable with 2, 3 or 5 in max 1 second
对于这个具体问题,我需要您的帮助。
a <= b [1,10 ^ 18]区间中有多少个数可被2、3或5除?
结果必须在最多1秒内运行!
标准程序将使用下面的for循环。
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);
但是,如果我输入大量数字,则程序需要很多时间才能得到结果。
范例1:
a = 11,b = 30,结果= 14
范例2:
a = 123456789012345678,b = 876543210987654321,结果= 552263376115226339
我想出了类似的东西
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);
}
解决方案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.