Generate Fibonacci number in Java

problem

Given a number n, you wish to generate the nth Fibonacci element. The formula is as follows:

fibonacci formula

SOLUTION

One solution is by using recursion. Fibonacci sequence is recursive by its natural definition so it will suit best. For example:

				
					public class Fibonacci {

    public long calculate(int n) {
        if (n==0) {
            return 0;
        }else if(n==1) {
            return 1;
        }else
            return calculate(n-1) + calculate(n-2);
        }
}
				
			
running

To quickly execute, let’s put it in the main method:

				
					public class Main {
    public static void main(String[] args) {
        long fibo10 = new Fibonacci().calculate(10);
        System.out.println(fibo10);
    }
}
				
			
output
55

Correct, the 10th element is 55. You can see the first 20 elements in the Fibonacci sequence are as follow:

F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F17 F18 F19 F20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

conclusion

This is a simple solution using Long as the return type and binary recursion (it’s calling twice the calculate() method). The downsides of this approach is that is limited to the return number and also quite slow. Can you try to execute this with n=40? It can be improved by using BigInteger as the return type and also dynamic programming to speed up the binary recursion.

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.