DEV Community

Discussion on: Project Euler #2 - Even Fibonacci numbers

Collapse
 
rahyhub profile image
rahy-hub

/*Even Fibonacci numbers

Problem 2
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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */

include

using namespace std;

int main()
{
int n1=1, n2=2 ,n3=0 , sumeven=0;

if(n1%2==0)
    sumeven+=n1;
if(n2%2==0)
    sumeven+=n2;
for(int i=1;n3<=4e6;i++) 
{
  n3=n1+n2;
  n1=n2;
  n2=n3;
if(n3%2==0)
    sumeven+=n3;

}

cout<<"the sum of the even-valued terms = "<<sumeven;

return 0;
}

C++ >> output>> 4613732