Próbuję rozwiązać problem nr 2 z listy Eulera - suma parzystych liczb poniżej 4 mln, ale niestety ciągle otrzymuję zły wynik. Żeby sobie ułatwić rozwiązanie, to znalazłem gotowy program który wygląda tak:
int sum = 0;
int x = 1; // Represents the current Fibonacci number being processed
int y = 2; // Represents the next Fibonacci number in the sequence
while (x <= 10) {
if (x % 2 == 0)
sum += x;
int z = x + y;
x = y;
y = z;
}
System.out.println(sum);
Dla uproszczenia policzyłem sumę dla 10 i już widzę że mój program inaczej działa - ten daję sumę 10 a mój 44.
Poniżej mój program
public static void main(String args[]) {
int max=10;
long sum=0;
int fibb[]= new int[max];
fibb[0]=0;
fibb[1]=1;
int i=0;
for(i=2;i<max;i++) {
fibb[i]=fibb[i-2]+fibb[i-1];
}
for(i=0;i<max;i++) {
if(fibb[i]%2==0) sum=sum+fibb[i];
System.out.println("Element " + i + " = "+ fibb[i]);
}
System.out.println("Suma= "+sum);
I wynik z 10-cioma pierwszymi elementami
Element 0 = 0
Element 1 = 1
Element 2 = 1
Element 3 = 2
Element 4 = 3
Element 5 = 5
Element 6 = 8
Element 7 = 13
Element 8 = 21
Element 9 = 34
Suma= 44
...czemu to jest źle - przecież 2+8+34 jest równe 44, wiec powinno być OK.