繁体   English   中英

如何在最多1秒的时间内找到可被2、3或5整除的数字

[英]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);
}

解决方案:

  • 它计算分别被2或3或5整除的数字并将其相加。
  • 现在我们需要舍弃两次计数的数字:对于2和3,它将是每6个数字,对于10个数字,将是2和5,对于每15个数字将是3和5
  • 最后,我们需要包含可被2、3和5整除的数字,这些数字在第2步中被丢弃,因此我们每30个数字相加一次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM