Created
August 13, 2014 11:05
-
-
Save JaDogg/0dde3d8aaf21d59df74f to your computer and use it in GitHub Desktop.
Euler2
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
int sum_even_fibonacci(int limit, int *steps_taken) { | |
int a = 1, b = 0; | |
int sum = 0; | |
int even_fibonacci = 0; | |
for (int steps = 1; even_fibonacci < limit; steps++) { | |
assert(a % 2); // Fibonacci just before even Fibonacci | |
assert(b % 2 == 0); // Even Fibonacci | |
sum += even_fibonacci; | |
even_fibonacci = 2 * a + 3 * b; | |
a += 2 * b; | |
b = even_fibonacci; | |
if (steps_taken) *steps_taken = steps; | |
} | |
return sum; | |
} | |
int main(int argc, char ** argv){ | |
if(argc!=2){ | |
printf("Invalid number of arguments\n"); | |
printf("Usage a.exe [limit]\n"); | |
return EXIT_FAILURE; | |
} | |
int limit = atoi(argv[1]); | |
if(limit < 3){ | |
printf("Invalid input\n"); | |
printf("Enter a limit of 3 or more\n"); | |
return EXIT_FAILURE; | |
} | |
int steps_taken = -1; | |
int sum = sum_even_fibonacci(limit,&steps_taken); | |
printf("Sum of the even-valued fibbonaci below %d\n",limit); | |
printf("Answer = %d, Steps Taken = %d\n",sum,steps_taken); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment