我试图找到甚至斐波纳契数的总和,直到400万。 我找到了这些数字,但我无法将它们加起来......在if(n%2 == 0)循环中
8
34
144
610
2584
10946
46368
196418
832040
3524578
public static void number2()
{
int number = 40;
int a, b, c;
int numLim = 0;
a = 1;
b = 2;
while(numLim < 4000000)
{
c = a + b;
a = b;
b = c;
numLim = b;
if(numLim > 4000000)
{
break;
}
int sum = 0;
if(numLim % 2 == 0)
{
System.out.println(numLim);
sum = sum + numLim;
System.out.println("sum :" +sum);
}
}
}
答案 0 :(得分:8)
您必须在sum
循环之外定义while
,否则每次迭代都会变为0
。
int sum = 0;
...
while ...
切记不要在每次迭代时将sum
设置为0。
答案 1 :(得分:0)
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 32; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
sum += fibonacci;
System.out.println("This is the sum " +sum);
}
}
}
所以我这样解决了它,它的效率更高,数学有效,但欧拉讨厌我,希望这会有所帮助。
答案 2 :(得分:0)
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 31; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
if (fibonacci%2 == 0) {
sum += fibonacci;
System.out.println(sum);
}
}
}
抱歉,此代码有效。
答案 3 :(得分:0)
试图在Java中执行上述操作,这是我的解决方案
public static void main(String[] args) {
int first = 1;
int second = 2;
int sum = 0;
int sumOfEvenValuedTerms = second;
for (int i = 0; i < 30; i++) {
sum = first + second;
if (sum <= 4000000) {
if (sum % 2 == 0) {
sumOfEvenValuedTerms += sum;
}
first = second;
second = sum;
}
}
System.out.println(sumOfEvenValuedTerms);
}
输出为4613732
答案 4 :(得分:0)
public static int getSumOfEvenNumbers(int n) {
int prev = 0;
int i =1;
int sum = 0;
while (i<n){
int nextNumber = i + prev;
if(nextNumber %2 ==0) {
System.out.println(nextNumber);
sum +=nextNumber;
}
prev = i;
i = nextNumber;
}
return sum;
}
答案 5 :(得分:0)
public class evenFib {
public static void main(String[] args) {
double a = 1, b = 2, c = 0, sum = 0;
for (double i = 0; i <= 1000; i++) {
c = a + b;
a = b;
b = c;
if (c % 2 == 0 && sum < 4000000) {
sum = sum + c;
}
}
System.out.println(sum + 2);
}
}