In: Computer Science
Implement the Fibonacci function by means of accumulative parameters so that it runs in linear time.
(Please use OCaml, Haskell or another functional language and delineate which you are using. Python won't work, unfortunately.)
C++ has some features that are functional in nature, partially.
#include<conio.h>
#include<stdio.h>
fab(int num) // defining function for fabonacci series
{ int a= 0, b= 1, c, i; // 'a' and 'b' for initial values, 'c' is storing sum of 'a' and 'b', 'i' is for iteration
if(num == 0) return a; // checking if given limit number is 0
for(i=2; i<= num; i++) // "i=2" because we have already printed first 2 numbers i.e "0" and "1", //so we start from 2
{ c= a+b; // c stores sum of "a" and "b" and then swapping takes place
// for eg. at begning when a=0 and b=1 then, c= 1, after swap= a=1 and b=1.
a=b;
b=c;
printf(" "%d", b); // printing fabonacci values
}
}
int main()
{ int lmt= 10;
printf("0 1"); // printing the first initial values that is "0" and "1".
fab(lmt); // calling the above function for fabonacci series
getchar();
return 0;
}
OUTPUT will be
0 1 1 2 3 5 8 13 21 34 55