c - Fibonacci Sequence Code -


the fibonacci numbers have range of interesting uses in mathematics , computer science. example, suppose single mould spores falls onto loaf of break while making breakfast 1 day. suppose 48 hours after spore created able clone itself, , create further fresh 1 every 24 hours thereafter. suppose 48 hours after created each new spore starts cloning fresh spore everyday.

in general f(n) = f(n-1) + f(n-2).

write program prints out number of spores present @ end of each day. stop when number of spores exceeds ten million. how many days take?

int days, next, first=0, second=1;  printf("enter day want know how many spores exists on\n"); scanf("%d", &days);  while(next < 10000000) {      if(days == 1) {         next = 1;     }     else {         next = first + second;         first = second;         second = next;     } } printf("the day %d has %d spores\n", days, next); 

so far i've been able this. it's taking me no where. can else using while, if , scanf functions ?

the fibonacci sequence operates following:

1 1 2 3 5 8 13 21 34 etc....

so comes down formula of f(n) = f(n-2) + f(n-1). missing code increment days.

try this:

days = 1; next = 0; first = 0; second = 1;  while(next < 10000000) {     next = first + second;     first = second;     second = next;     printf("the day %d has %d spores\n", days, next);     days++; } 

that should generate proper fibonacci number sequence. if not, i'll correct it.

edit: noticed printf statement not inside while loop. furthermore, notice how setup variables before entered loop not require if statement inside loop. it's more of performance issue less stuff there inside loop, faster execute.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -