Problem:
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.
Solution:
#include <stdio.h>
#include <stdlib.h>
void print_answer(int limit){
int a = 1; //1st term
int b = 2; //2nd term
int even_fibbonaci = 0; //start as zero,because of the loop
int sum = 2;//sum of even up to 2nd term
int steps_taken = 0;
do{
sum += even_fibbonaci;
even_fibbonaci = 2*a + 3*b; //even fibbonaci
a += 2*b; //fibbonaci just before even fibbonaci
b = even_fibbonaci;
steps_taken++;
}while(even_fibbonaci<limit);
printf("Sum of the even-valued fibbonaci below %d\n",limit);
printf("Answer = %d, Steps Taken = %d\n",sum,steps_taken);
}
int main(int argc, char ** argv){
if(argc!=2){
printf("Invalid number of arguments\n");
printf("Usage a.exe [limit]\n");
return -1;
}
int limit = atoi(argv[1]);
if(limit < 3){
printf("Invalid input\n");
printf("Enter a limit of 3 or more\n");
return -1;
}
print_answer(limit);
return 0;
}
For limit = 4000000
Execute as {executable} [limit]
Sum of the even-valued fibbonaci below 4000000
answer = 4613732, steps taken = 11
Compiler: