In this tutorial, we will see “Two ways to find Nth Fibonacci Number using Java?”find nth Fibonacci number in java 8
Java – Multiple ways to find Nth Fibonacci Number Click To Tweet
Java 1st method (before JAVA 8):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /** * Using Java, Find the Nth Number in Fibonacci Series * @author Deepak Verma * */ import java.util.HashMap; import java.util.Map; public class Find_Nth_Fibonacci_Number_Java_Example { private Map<Integer, Long> memo = new HashMap<>(); public long fib(int n) { if (n <= 0) { return 0; } else if (n == 1) { return 1; } else if (memo.containsKey(n)) { return memo.get(n); } long result = fib(n - 1) + fib(n - 2); memo.put(n, result); return result; } public static void main(String[] args) { Find_Nth_Fibonacci_Number_Java_Example fibValue = new Find_Nth_Fibonacci_Number_Java_Example(); int n = 10; System.out.println("The " + n + "th Fibonacci number is: " + fibValue.fib(n)); } } |
Output:
1 | The 10th Fibonacci number is: 55 |
check if text or string present in a file using java 8
Java 2nd method (using JAVA 8):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import java.util.stream.Stream; public class Find_Nth_Fibonacci_Number_Java8_Example { public static long fib(int n) { return Stream.iterate(new long[] {1, 1}, f -> new long[] { f[1], f[0] + f[1] }) .limit(n) .reduce((a, b) -> b) .get()[0]; } public static void main(String[] args) { int n = 10; System.out.println("The " + n + "th Fibonacci number is: " + Find_Nth_Fibonacci_Number_Java8_Example.fib(n)); } } |
Output:
1 | The 10th Fibonacci number is: 55 |
generate random number within range in java
find nth Fibonacci number in java 8
Java – Multiple ways to find Nth Fibonacci Number Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: