|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * |
| 8 | + * @author Varun Upadhyay (https://github.com/varunu28) |
| 9 | + * |
| 10 | + */ |
| 11 | + |
| 12 | +public class Fibonacci { |
| 13 | + |
| 14 | + public static Map<Integer,Integer> map = new HashMap<Integer,Integer>(); |
| 15 | + |
| 16 | + public static void main(String[] args) throws Exception { |
| 17 | + |
| 18 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 19 | + int n = Integer.parseInt(br.readLine()); |
| 20 | + |
| 21 | + System.out.println(fibMemo(n)); // Returns 8 for n = 6 |
| 22 | + System.out.println(fibBotUp(n)); // Returns 8 for n = 6 |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * This method finds the nth fibonacci number using memoization technique |
| 27 | + * |
| 28 | + * @param n The input n for which we have to determine the fibonacci number |
| 29 | + * Outputs the nth fibonacci number |
| 30 | + **/ |
| 31 | + |
| 32 | + public static int fibMemo(int n) { |
| 33 | + if (map.containsKey(n)) { |
| 34 | + return map.get(n); |
| 35 | + } |
| 36 | + |
| 37 | + int f; |
| 38 | + |
| 39 | + if (n <= 2) { |
| 40 | + f = 1; |
| 41 | + } |
| 42 | + else { |
| 43 | + f = fib(n-1) + fib(n-2); |
| 44 | + map.put(n,f); |
| 45 | + } |
| 46 | + |
| 47 | + return f; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * This method finds the nth fibonacci number using bottom up |
| 52 | + * |
| 53 | + * @param n The input n for which we have to determine the fibonacci number |
| 54 | + * Outputs the nth fibonacci number |
| 55 | + **/ |
| 56 | + |
| 57 | + public static int fibBotUp(int n) { |
| 58 | + |
| 59 | + Map<Integer,Integer> fib = new HashMap<Integer,Integer>(); |
| 60 | + |
| 61 | + for (int i=1;i<n+1;i++) { |
| 62 | + int f = 1; |
| 63 | + if (i<=2) { |
| 64 | + f = 1; |
| 65 | + } |
| 66 | + else { |
| 67 | + f = fib.get(i-1) + fib.get(i-2); |
| 68 | + } |
| 69 | + fib.put(i, f); |
| 70 | + } |
| 71 | + |
| 72 | + return fib.get(n); |
| 73 | + } |
| 74 | +} |
| 75 | + |
0 commit comments