题目链接:http://ac.jobdu.com/problem.php?cid=1039&pid=3
题目描述:
题目描述: 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。斐波那契数列的定义如下: 输入: 输入可能包含多个测试样例,对于每个测试案例, 输入包括一个整数n(1<=n<=70)。 输出: 对应每个测试案例, 输出第n项斐波那契数列的值。 样例输入: 3样例输出: 2
用Java中的大数 BigInteger 可以很快的求解,不过我还是得到Runtime Error的结果
import java.math.BigInteger; import java.util.Scanner; /** * 题目四:斐波那契数列 * * @author yinger */ public class NineOj_t4 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; while (scanner.hasNextInt()) { n = scanner.nextInt(); System.out.println(fab(n)); } } public static BigInteger fab(int n) { if (n == 0) { return BigInteger.ZERO; } else if (n == 1) { return BigInteger.ONE; } BigInteger result = BigInteger.ZERO; BigInteger num1 = BigInteger.ONE; BigInteger num2 = BigInteger.ONE; for (int i = 1; i < n; i++) { result = num2.add(num1); num1 = num2; num2 = result; } return result; } }