Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Last active December 19, 2015 06:59
Show Gist options
  • Save rfaisal/5915787 to your computer and use it in GitHub Desktop.
Save rfaisal/5915787 to your computer and use it in GitHub Desktop.
package dynamic_programming;
/**
* Calculate the Fibonacci numbers up to n.
* When calculated, any Fibonacci number <=n can be returned without recalculating.
* Class Contributors: Faisal Rahman
* @author Faisal Rahman
*
*/
public class Fibonacci {
private int n;
/**
* Needed for dynamic programming algorithm.
*/
private int []table;
public Fibonacci(int n) throws Exception {
if(n<0)
throw new Exception("Wrong value of n.");
this.n=n;
table= new int[n+1];
}
/**
* A dynamic programming implementation.
*/
public void calculate(){
if(n>=0) table[0]=0;
if(n>=1) table[1]=1;
for(int j=2;j<=n;j++)
table[j]=table[j-1]+table[j-2];
}
public int get(int i) throws Exception{
if(i<0)
throw new Exception("Wrong value of i.");
if(i>n)
throw new Exception("Fibo up to "+i+" is not calculated.");
else
return table[i];
}
}
/**
* Problem owner: Faisal Rahman
* Problem contributors: Faisal Rahman
**/
#include<stdio.h>
/**
* nth fibonacci number
**/
int fibonacci(int n){
if(n<1) return 0;
else if(n==1 || n==2) return 1;
else return fibonacci(n-1)+fibonacci(n-2);
}
/**
* USAGE: ./a.out 5 [5th fibonachi]
**/
int main(int argc, char *argv[]){
if(argc<2) return 1;
int n = atoi(argv[1]);
printf("%d ",fibonacci(n));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment