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 Share on X

Java 1st method (before JAVA 8):

/**
 * 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:

The 10th Fibonacci number is: 55

check if text or string present in a file using java 8

Java 2nd method (using JAVA 8):

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:

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 Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts