java - 如何在输出中显示大于 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
实际结果总是前四个。
解决方案
只要等待足够长的时间。
计算第三个数字需要 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)
如果您告诉我们该程序永远不会退出,那将会很有帮助。
推荐阅读
- c - 在计算 SUNDIALS/CVODES 中的伴随灵敏度时,如何处理正解中的不连续性?
- python - 我可以使用布尔函数作为 SciPy 的非线性约束吗?
- python - 我想为 Ceasar Cipher 构建一个 Python 程序
- java - 如何将Resultset Jpa分配给Hashmap
- javascript - 如何从ajax响应中获取数据?
- docker - Windows 10 Pro 机器上的 Docker 桌面安装
- ethereum - Chainlink v0.8 智能合约部署问题
- java - Java 摇摆 | 最后一个 JTextField 未设置为自定义大小
- graph - 返回“标签的最大粉丝”neo4j
- php - 准备好的语句和执行中的重复列名