(斐波那契总结)Write a method to generate the nth Fibonacci number (CC150 8.1)
根据CC150的解决方式和Introduction to Java programming总结:
使用了两种方式,递归和迭代
CC150提供的代码比较简洁,不过某些细节需要分析。
现在直接运行代码,输入n(其中用number代替,以免和方法中的n混淆)的值,可以得出斐波那契数。
代码如下:
/* CC150 8.1 Write a method to generate the nth Fibonacci number Author : Mengyang Rao note : Use two methods ,Iteration and Recursion Date : 2015-02-25 23:56:00 */ import java.util.Scanner; public class TestFibonacci { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter n :"); int number = input.nextInt(); System.out.println("The Iteration number is : " + fibonacci(number) + "\n n value is : " + number); System.out.println("The Recursion number is : " + fibo(number) + "\n n value is : " + number); } // Version: Recursion public static long fibo(long n ) { if(n == 0) return 0; else if (n == 1) return 1; else if (n > 1) return fibo(n - 1) + fibo(n - 2); else return -1; } // Version: Iteration public static long fibonacci(long n) { int a = 0, b = 1; if (n < 0) return -1; else if (n == 0) return 0; for (int i = 3; i <= n; i++) { int c = a + b; a = b; b = c; } return b; } }