Skip to content

Instantly share code, notes, and snippets.

@CraigRodrigues CraigRodrigues/problem2.c Secret
Created Jun 29, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.