gpt4 book ai didi

Euler 项目 #12 的 Java 代码

转载 作者:行者123 更新时间:2023-12-01 18:44:45 26 4
gpt4 key购买 nike

我正在研究 Project Euler 的问题 #12,具体内容如下:

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 class Euler12 {
public static void main (String[] args) {
int i = 1;
int x = 2;
boolean found = false;
while (!found) {
if (divisors(i) > 500) {
System.out.println(i);
found = true;
}
else {
i +=x;
x++;
}
}
}

public static int divisors (int n) {
int counter = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) counter++;
}
return counter;
}
}

最佳答案

运行程序后,似乎它的运行时间非常长,看看你的算法,确实如此(我以前做过这个问题)。您需要优化“除数”

剧透

如果将 for (int i = 1; i <= n; i++) 改为 for (int i = 1; i*i <= n; i++),将会大大减少执行时间。

更新:在不进行更改的情况下运行后,4 分钟内没有答案,这违反了 Project Euler 的一分钟规则。更改后,十秒内得到答复。享受吧:)

关于Euler 项目 #12 的 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com