Примеры Фибоначчи
Fibonacci number - Каждое число после первых двух является суммой двух предыдущих.
Несколько примеров Java, чтобы найти числа Фибоначчи.
1. Поток Java 8
1.1 In Java 8, we can use Stream.iterate
to generate Fibonacci numbers like this :
Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(10) .forEach(x -> System.out.println("{" + x[0] + "," + x[1] + "}"));
Выход
{0,1} {1,1} {1,2} {2,3} {3,5} {5,8} {8,13} {13,21} {21,34} {34,55}
P.S Review the above output, the first value is what we wanted.
1.2 Final version.
Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(10) .map(t -> t[0]) .forEach(x -> System.out.println(x));
Выход
0 1 1 2 3 5 8 13 21 34
1.3 Sum all the Fibonacci numbers
int sum = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(10) .map(t -> t[0]) .mapToInt(Integer::intValue) .sum(); System.out.println("Total : " + sum);
Выход
Total : 88
1.4 Join with commas.
String collect = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(10) .map(t -> t[0]) .map(String::valueOf) // convert to string .collect(Collectors.joining(", ")); System.out.println("Result : " + collect);
Выход
Result : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
1.5 A function to create a List of Fibonacci numbers.
package com.example.concurrency; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class Fibonacci { public static ListgetFibonacci(int series) { return Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(series) .map(n -> n[0]) .collect(toList()); } public static void main(String[] args) { List fibonacci = getFibonacci(10); fibonacci.forEach(x -> System.out.println(x)); } }
Выход
0 1 1 2 3 5 8 13 21 34
1.6 The type int
and long
are not enough to store larger Fibonacci numbers. Ниже приведен примерBigInteger
для поиска первого миллиона чисел Фибоначчи.
package com.example.concurrency; import java.math.BigInteger; import java.util.stream.Stream; public class Fibonacci { public static BigInteger getFibonacci(int series) { return Stream.iterate(new BigInteger[]{ BigInteger.ZERO, BigInteger.ONE}, t -> new BigInteger[]{t[1], t[0].add(t[1])}) .limit(series) .map(n -> n[1]) // find, we need n[1] .reduce((a, b) -> b).orElse(BigInteger.ZERO); } public static void main(String[] args) { System.out.println(Fibonacci.getFibonacci(1_000_000)); } }
Выход
1953282128707757731632014947596256332443... // 208,988 digits!!!, too long to display here
2. Рекурсивная петля
2.1 Java recursive loop example to create a list of Fibonacci numbers. Хорошо только для демонстрации, этот рекурсивный цикл медленный.
Fibonacci.java
package com.example.concurrency; public class Fibonacci { public static int fib(int n) { if (n <= 1) return n; else return fib(n - 1) + fib(n - 2); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(fib(i)); } } }
Выход
0 1 1 2 3 5 8 13 21 34
2.2 How it works?
fib(n) = fib(n - 1) + fib(n - 2); fib(5) = fib(4) + fib(3); fib(4) = fib(3) + fib(2); fib(3) = fib(2) + fib(1); fib(2) = fib(1) + fib(0); fib(1) = 1 fib(0) = 1
3. Нормальный цикл
3.1 Java normal loop to find the Fibonacci numbers, simple and easy.
Fibonacci.java
package com.example.concurrency; import java.math.BigInteger; public class Fibonacci { public static int fib(int n) { if (n <= 1) return n; int previous = 0, next = 1, sum; for (int i = 2; i <= n; i++) { sum = previous; previous = next; next = sum + previous; } return next; } public static BigInteger fib2(int n) { if (n <= 1) return BigInteger.valueOf(n); BigInteger previous = BigInteger.ZERO, next = BigInteger.ONE, sum; for (int i = 2; i <= n; i++) { sum = previous; previous = next; next = sum.add(previous); } return next; } public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(fib(i)); } System.out.println("---"); for (int i = 0; i < 10; i++) { System.out.println(fib2(i)); } System.out.println("---"); System.out.println(fib(100)); //overflow System.out.println(fib2(100)); } }
Выход
0 1 1 2 3 5 8 13 21 34 --- 0 1 1 2 3 5 8 13 21 34 --- -980107325 354224848179261915075
Note
ИспользуйтеBigInteger
для хранения чисел Фибоначчи, чтобы избежать проблемы переполнения.