Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions DynamicProgramming/Fibonacci.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package DynamicProgramming;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
* @author Varun Upadhyay (https://github.com/varunu28)
Expand All @@ -13,14 +12,16 @@ public class Fibonacci {

private static Map<Integer, Integer> map = new HashMap<>();

public static void main(String[] args) throws Exception {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size = Integer.parseInt(br.readLine());
public static void main(String[] args) {

// Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]
System.out.println(fibMemo(size));
System.out.println(fibBotUp(size));
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

System.out.println(fibMemo(n));
System.out.println(fibBotUp(n));
System.out.println(fibOptimized(n));
}

/**
Expand All @@ -29,7 +30,7 @@ public static void main(String[] args) throws Exception {
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/
private static int fibMemo(int n) {
public static int fibMemo(int n) {
if (map.containsKey(n)) {
return map.get(n);
}
Expand All @@ -51,7 +52,7 @@ private static int fibMemo(int n) {
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/
private static int fibBotUp(int n) {
public static int fibBotUp(int n) {

Map<Integer, Integer> fib = new HashMap<>();

Expand Down Expand Up @@ -83,16 +84,16 @@ private static int fibBotUp(int n) {
* Whereas , the above functions will take O(n) Space.
* @author Shoaib Rayeen (https://github.com/shoaibrayeen)
**/
private static int fibOptimized(int n) {
public static int fibOptimized(int n) {
if (n == 0) {
return 0;
}
int prev = 0, res = 1, next;
for (int i = 2; i < n; i++) {
for (int i = 2; i <= n; i++) {
next = prev + res;
prev = res;
res = next;
}
return res;
}
}
}