我正在尝试解决Java中的第12个Euler问题,我似乎真的无法理解这里的问题。该脚本旨在输出除以500的除数的第一个三角数,如代码注释中所述。正确的答案应该是“ 76576500”,而我的脚本输出的答案是“ 842161320”-幅度很大。有人知道我要去哪里错吗?感谢所有帮助,谢谢!
public class Script_012
{
/*
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
*/
public static void main (String [] args)
{
boolean enough_factors = false;
long num = 1;
long runner = 1;
int num_of_factors;
int highest_factors = 0;
while (!enough_factors)
{
num_of_factors = 0;
for (int i = 1; i < (int) Math.sqrt(num); i ++)
{
if ((num % i) == 0)
{
num_of_factors += 1;
}
}
if (num_of_factors > 500)
{
enough_factors = true;
System.out.println(num);
}
runner += 1;
num += runner;
}
}
}
答案 0 :(得分:2)
问题是您只添加了小于或等于平方根的因数,但问题是有关所有因素,包括大于平方根的因数。
简单(但缓慢)的解决方案:
将for (int i = 1; i < (int) Math.sqrt(num); i ++)
更改为for (int i = 1; i <= num; i ++)
更好的解决方案: 保持for循环的迭代次数相同,但是每次加2,并且只考虑平方根。 代码:
public static void main (String [] args)
{
boolean enough_factors = false;
long num = 1;
long runner = 1;
int num_of_factors;
int highest_factors = 0;
while (!enough_factors)
{
num_of_factors = 0;
for (int i = 1; i < (int) Math.sqrt(num); i ++)
{
if ((num % i) == 0)
{
num_of_factors += 2;
}
}
if(num % Math.sqrt(num) == 0) {
num_of_factors++;
}
if (num_of_factors > 500)
{
enough_factors = true;
System.out.println(num);
}
runner += 1;
num += runner;
}
}