java - Sum of even Fibonacci -


i not sure why code produces wrong negative value when put 4000000 method's parameter size, i.e. fib(4000000)?

the question asks:

each new term in fibonacci sequence generated adding previous 2 terms. starting 1 , 2, first 10 terms be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

by considering terms in fibonacci sequence values not exceed 4 million, find sum of even-valued terms.

my first code:

public void fib(int k) {      int result = 0;     int[] array = new int[k];     array[0] = 1;     array[1] = 2;      (int = 2; < k; i++) {         array[i] = array[i - 2] + array[i - 1];            }      (int even: array) {          if (even % 2 == 0) {             result += even;         }     }             system.out.println(result); } 

which didn't work assumed because array size big (four million lot) tried write different code:

public void fib(int k) {      int sum = 0;     int term1 = 1;     int term2 = 2;     int term3 = 0;     int = 2;      while (i < k) {          term3 = term1 + term2;          term1 = term2;         term2 = term3;         i++;          if (term2 % 2 == 0) {             sum += term2;         }     }         system.out.println(sum + 2);  } 

which didn't work.

what wrong code? small numbers of size works large doesn't.

after googled answer question found:

    int term1 = 1;     int term2 = 2;     int = 0;     int result = 0;      while (term1 < 4000000) {         = term1;         term1 = term2;         term2 = term2 + i;          if (term2 % 2 == 0) {             result += term2;         }     }     system.out.println(result); 

which works.

i don't think you're running overflow issue. think you're reading problem incorrectly. says should @ fibonacci numbers value of number <= 4 million. instead, you're looking @ first 4 million fibonacci numbers. it's difference between this:

1, 2, 3, 5, 8 (all fib numbers less 10)

and this:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89 (the first 10 fib numbers)

i think wants former, you're doing latter.

instead of doing:

while (i < k) { 

what if this?

while (term1 < k) { 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -