Created
January 17, 2016 08:22
-
-
Save ivanarrizabalaga/58635fabbc36e7ea5b85 to your computer and use it in GitHub Desktop.
Classic fibonacci problem solved with a linear approach
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
int fib(int n){ | |
if(n<=2){ | |
return 1 | |
} | |
int i=3; | |
int i1=1; | |
int i2=1; | |
int sum; | |
while(i!=n){ | |
sum=i1+i2 | |
i2=i1 | |
i1=sum | |
i++; | |
} | |
return i1+i2 | |
} | |
assert fib(1)==1 | |
assert fib(2)==1 | |
assert fib(3)==2 | |
assert fib(4)==3 | |
assert fib(5)==5 | |
assert fib(6)==8 | |
assert fib(7)==13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment