Skip to content

Instantly share code, notes, and snippets.

@krfong916
Last active September 9, 2019 22:04
Show Gist options
  • Save krfong916/bd7dc42e7f6c6c56072177c5bccfd655 to your computer and use it in GitHub Desktop.
Save krfong916/bd7dc42e7f6c6c56072177c5bccfd655 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
class Fibonacci {
/**
* We can represent the fibonacci sequence as an array
*/
int fibIterative (int n) {
// we define the size of array as n+2 to accomodate the base cases, f[0] & f[1]
int[] f = new int[n+2];
f[0] = 0;
f[1] = 1;
// build the sequence using the fibonacci definition f(n) = f(n-1) + f(n-2)
for (int i = 2; i <= 2; i++) {
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
int fibRecursive (int n) {}
static int getUserInput() {
System.out.println("This is a program to compute the fibonacci number based on your input");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
while (!sc.hasNextInt()) {
sc.next();
System.out.println("Please enter a positive integer: ");
}
return sc.nextInt();
}
static void printFibonacci(int n) {
System.out.println("The fibonacci number of your input is: " + n);
}
public static void main (String[] args) {
int n, result;
n = getUserInput();
result = fibIterative(n);
printFibonacci(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment