Je n'arrive pas à comprendre pourquoi le code suivant ne produit pas la sortie attendue. A la place, résultat = 272 ce qui ne semble pas correct.Trouver la somme de tous les termes pairs dans la séquence Fibonacci
/*
*Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
*Find the sum of all the even-valued terms in the sequence which do not exceed four million.
*/
public class Fibonacci
{
public static void main (String[] args)
{
int result = 0;
for(int i=2;i<=33;i++)
{
System.out.println("i:" + fib(i));
if(i % 2 == 0) //if i is even
{
result += i;
System.out.println("result:" + result);
}
}
}
public static long fib(int n)
{
if (n <= 1)
return n;
else
return fib(n-1) + fib(n-2);
}
}
En outre, la ligne 'if (i% 2 == 0)' ne teste pas si un nombre * Fibonacci * est pair. – rampion
@rampion: Oui; cela aussi. (Je pensais qu'il voulait vraiment même _inidicies_) – SLaks
je l'ai eu. Merci! – kachilous