-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathFibonacci.java
39 lines (33 loc) · 1.06 KB
/
Fibonacci.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* This is a algorithm to implement the Fibonacci Nth element problem
* using dynamic programming paradigm. This version I am using the memoization
* strategy to going top-down to find all needed values and store on the fiboMemo array.
*
* @author Augusto Baltazar (augusto.jaba@gmail.com)
*/
public class Fibonacci {
private int[] fiboMemo;
private int findNthElement(int n) {
if (this.fiboMemo == null) {
fiboMemo = new int[n + 1];
}
if (n <= 1) {
fiboMemo[n] = n;
} else {
fiboMemo[n] = findNthElement(n - 1) + findNthElement(n - 2);
}
return fiboMemo[n];
}
/**
* Tests the function to the given number passed as argument
* @param args
*/
public static void main(String[] args) {
try {
int arg = Integer.parseInt(args[0]);
System.out.println(new Fibonacci().findNthElement(arg));
} catch (Exception e) {
System.out.println("The argument entered is not a valid integer number.");
}
}
}