-
-
Save CraigRodrigues/591b90bdde5e475b4e4e0e0b10b0bd8d to your computer and use it in GitHub Desktop.
Project Euler - Problem 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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