Skip to content

Instantly share code, notes, and snippets.

@kylethedeveloper
Created April 9, 2018 18:32
Show Gist options
  • Save kylethedeveloper/a6f2955abcf62caa05db74bcec545864 to your computer and use it in GitHub Desktop.
Save kylethedeveloper/a6f2955abcf62caa05db74bcec545864 to your computer and use it in GitHub Desktop.
Project Euler - Problem 2 - Even Fibonacci numbers
/*
Project_2.cpp : Even Fibonacci numbers
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 <iostream>
using namespace std;
int main()
{
int a = 0, b = 1, c = 0;
unsigned int sum = 0;
while (c < 4000000) // as values do not exceed four million
{
c = a + b; // sum of last two terms
a = b; // 2nd previous
b = c; // 1st previous
if (c % 2 == 0) // check for even
{
sum += c; // sum of evens
}
}
cout << "Last term of Fibonacci: " << c << endl;
cout << "Sum of even numbers: " << sum << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment