首页 > 解决方案 > 如何在输出中显示大于 8128 的完美数字

问题描述

我正在尝试一些关于完美数字的代码,我写了一个代码应该显示我要求的前 n 个完美数字,但它只显示前 4 个数字,总是......

我已经尝试用各种柜台等换地方,但这些都不起作用

public static void main(String[]args){
    int n; //counter
    long N = 6; //starting point of the perfect numbers
    System.out.print("Please enter n: "); //maximum value of the counter
    n = in.nextInt();
    while (n > 0) { //first loop and control of the counter
        int sum = 0, i = 1; //initialization of the variables i need for the following loop
        while (i < N -1) { //control for the iterations, maximum value is N - 1(all the numbers except N) 
            if (N % i == 0) { //control if i is a divider
                sum = sum + i; // if i ist a divider than i add it to the variable sum
            }
            i++; // i increment
        }
        if (sum == N) { //final control, if sum is equal to N, than i print it
            System.out.print(N + " ");
            n--; //decrement of the counter, so that it shows me only the numbers i ask
        }
        N++; //increment of the number to control
    }
}

它应该显示我问的前 n 个数字,例如 n = 5 结果 6、28、496、8128、33550336

实际结果总是前四个。

标签: java

解决方案


只要等待足够长的时间。

计算第三个数字需要 30 毫秒,计算第四个数字需要 10 秒。

要达到数字 20.000,已经需要 53 秒。因此对于 33.000.000,可能需要 87.450 秒 = 24.3 小时。甚至更长,因为它看起来不是线性的:

6 after  0.0
28 after  0.0
496 after  0.033
8128 after  10.38
10000 ...  5.54
20000 ...  53.01    (estimate 24 h)
30000 ...  132.63
40000 ...  244.09
50000 ...  387.71
60000 ...  563.20   (estimate 86 h)
70000 ...  771.75
80000 ...  1010.81  (estimate 115 h)

进步

如果您告诉我们该程序永远不会退出,那将会很有帮助。


推荐阅读