1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.math.BigInteger; public class Fib { public static void main(String[] args) { System.out.println(fib(40)); } private static BigInteger fib(int n) { if (n == 0) { return BigInteger.ZERO; } else if (n == 1) { return BigInteger.ONE; } return fib(n - 1).add(fib(n - 2)); } } |
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 | import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class FibMemoized { public static void main(String[] args) { System.out.println(fib(100)); } private static Map<Integer, BigInteger> lookupTable = new HashMap<>(); static { lookupTable.put(0, BigInteger.ZERO); lookupTable.put(1, BigInteger.ONE); } private static BigInteger fib(int n) { if (lookupTable.containsKey(n)) { return lookupTable.get(n); } else { BigInteger result = fib(n - 1).add(fib(n - 2)); lookupTable.put(n, result); return result; } } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |