实现斐波那契数列
常规算法、递归算法
package com.code.ggsddu;
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
System.out.print("请输入数列长度:");
Scanner scanner = new Scanner(System.in);
int index = scanner.nextInt();
System.out.println("常规思路:");
System.out.print("数列前" + index + "项:");
byConventional(index);
System.out.println();
System.out.println("递归算法:");
System.out.println("数列第" + index + "项:" + byRecursion(index));
System.out.println("数列前" + index + "项:");
for (int n = 1; n <= index; n++) {
System.out.print(byRecursion(n) + "\t");
if (n % 5 == 0) {
System.out.println();
}
}
}
/**
* 常规算法
* 打印斐波那契数列前n项
*
* @param n 总项数、数列总长度
*/
public static void byConventional(int n) {
// 后一项等于前面两项之和
int previous = 1;
int middle = 1;
int next = 0;
for (int i = 1; i <= n; i++) {
if (i == 1 || i == 2) {
System.out.print(1 + " ");
} else {
next = previous + middle;
previous = middle;
middle = next;
System.out.print(next + " ");
}
}
System.out.println();
}
/**
* 递归算法
* 获取斐波那契数列第n项
*
* @param n 数组下标
* @return
*/
public static int byRecursion(int n) {
if (n == 1 || n == 2) {
return 1;
}
return byRecursion(n - 1) + byRecursion(n - 2);
}
}
控制台:
请输入数列长度:10
常规思路:
数列前10项:1 1 2 3 5 8 13 21 34 55
递归算法:
数列第10项:55
数列前10项:
1 1 2 3 5
8 13 21 34 55
Process finished with exit code 0
利用 jdk8 API 实现斐波那契数列
package com.demo.jdk8.stream;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FibonacciStream {
public static void main(String[] args) {
Stream<Long> fibonacci = Stream.generate(new FibonacciSupplier());
// 获得前10项
List<Long> collect = fibonacci.limit(5).collect(Collectors.toList());
collect.stream().forEach(System.out::println);
// 获得第6~10项
// List<Long> list = fibonacci.skip(5).limit(5).collect(Collectors.toList());
// list.stream().forEach(System.out::println);
}
}
class FibonacciSupplier implements Supplier<Long> {
long a = 0L;
long b = 1L;
@Override
public Long get() {
long c = a + b;
a = b;
b = c;
return a;
}
}
控制台:
1
1
2
3
5