标签:import class param next public java main ext str
不递归
package com.ikoo; public class NoRecursion { public static void main(String[] args) { int front = 1; int center = 1; int after = 0; for (int i = 1; i <= 10; i++) { if (i == 1 || i == 2) { System.out.print(1 + " "); } else { after = front + center; front = center;// 第二个数作为下一次求和第一个数 center = after;// 第三个数作为下一次求个的第二个数 System.out.print(after + " "); } } } }
1 1 2 3 5 8 13 21 34 55
递归
package com.ikoo; import java.util.Scanner; public class FibonacciSequence { public static void main(String[] args) { System.out.print("输入数列长度:"); Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); for (int i = 1; i <= num; i++) { System.out.print(getFibonacci(i) + "\t"); if (i % 5 == 0) { System.out.println(); } } } /** * 递归思想 * * @param i 数列长度(也对应着数列下标) * @return 数列中第 i 位上的对应的值 */ public static int getFibonacci(int i) { if (i == 1 || i == 2) { return 1; } return getFibonacci(i - 1) + getFibonacci(i - 2); } }
输入数列长度:10 1 1 2 3 5 8 13 21 34 55
递归 - 数组
package com.ikoo; import java.util.Arrays; import java.util.Scanner; public class FibonacciArray { public static void main(String[] args) { System.out.print("输入斐波那契数列长度:"); Scanner scanner = new Scanner(System.in); int len = scanner.nextInt(); int[] arr = new int[len]; FibonacciArray.getFibonacc(arr); } /** * 递归思想 - 数组 * * @param arr */ public static void getFibonacc(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i == 0 || i == 1) { arr[i] = 1; } else { arr[i] = arr[i - 1] + arr[i - 2]; } } System.out.println(Arrays.toString(arr)); } }
输入斐波那契数列长度:10 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
标签:import class param next public java main ext str
原文地址:http://www.cnblogs.com/ikoo4396/p/7464000.html