public class Three {
public static void main(String[] args) {
Three obj = new Three();
obj.function(600851475143);
}
private Long function(long i) {
Stack<Long> stack = new Stack<Long>();
for (long j = 2; j <= i; j++) {
if (i % j == 0) {
stack.push(j);
}
}
return stack.pop();
}
}
Run Code Online (Sandbox Code Playgroud)
运行上面的代码时,它会在行上产生错误obj.function(600851475143);.为什么?
我正在研究Project Euler问题#2:
Fibonacci序列中的每个新术语都是通过添加前两个术语生成的.从1和2开始,前10个术语将是:
1,2,3,5,8,13,21,34,55,89 ......
找出序列中所有偶数值的总和,不超过四百万.
我的代码:
public class Two {
public static void main(String[] args) {
Two obj = new Two();
int sum = 0, i = 1;
while (obj.fibonacci(i) < 4000001) {
if (obj.fibonacci(i) % 2 == 0) {
sum += obj.fibonacci(i);
i++;
}
}
System.out.println(sum);
}
public int fibonacci(int n) {
if (n == 0) {
return -1;
}
if (n == 1) {
return 1;
}
if (n == 2) {
return 3;
} …Run Code Online (Sandbox Code Playgroud)