Merge pull request #1009 from MatheusMuriel/master

Correction of iteration limit of fibOptimized
This commit is contained in:
Yang Libin
2019-10-24 14:40:14 +08:00
committed by GitHub

View File

@ -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)
@ -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));
}
/**
@ -29,7 +30,7 @@ public class Fibonacci {
* @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);
}
@ -51,7 +52,7 @@ public class Fibonacci {
* @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<>();
@ -83,16 +84,16 @@ public class Fibonacci {
* 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;
}
}
}