Skip to content

Instantly share code, notes, and snippets.

@CraigRodrigues
Created June 29, 2016 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CraigRodrigues/591b90bdde5e475b4e4e0e0b10b0bd8d to your computer and use it in GitHub Desktop.
Save CraigRodrigues/591b90bdde5e475b4e4e0e0b10b0bd8d to your computer and use it in GitHub Desktop.
Project Euler - Problem 2
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
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.
*/
//prototype
int fib(int x);
int main(void)
{
int n = 4000000;
int sum = 0;
for(int i = 1; i < 34; i++)
{
if (fib(i) <= n)
{
if (fib(i) % 2 == 0)
sum += fib(i);
}
}
printf("Final sum = %i\n", sum);
}
// returns next fibonacci number
int fib(int x)
{
if (x == 0)
return 0;
else if (x == 1)
return 1;
else
return (fib(x-1) + fib(x-2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment