Skip to content

Instantly share code, notes, and snippets.

@ivanarrizabalaga
Created January 17, 2016 08:22
Show Gist options
  • Save ivanarrizabalaga/58635fabbc36e7ea5b85 to your computer and use it in GitHub Desktop.
Save ivanarrizabalaga/58635fabbc36e7ea5b85 to your computer and use it in GitHub Desktop.
Classic fibonacci problem solved with a linear approach
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