[JAVA] A rudimentary note on the Fibonacci sequence


・ Fibonacci sequence

The ** Fibonacci sequence ** is a sequence derived from the "Rabbit Arithmetic" conceived by the Italian mathematician Leonardo Fibonacci. This sequence appears in many phenomena in the natural world, and it is said that the law of ** Fibonacci sequence ** works on the sequence of sunflower seeds.

When the nth Fibonacci number is represented by Fn, Fn recursively

F0 = 0
F1 = 1

Fn+2 = Fn + Fn+1 (n≧0)

Defined in.


The sum of the first and second values ​​gives the third value. In other words, the number obtained by adding the previous value and the previous two values ​​is the next number.

・ Code actually written

public class TryJava0120 {
	
	public static void main(String[] args) {
		
		int f0, f1, fn;
		
		f0 = 0;
		System.out.println("f0= " + f0);
		
		f1 = 1;
		System.out.println("f1= " + f1);
		
		for (int i = 2; i <= 20; i++) {
			fn = f0 + f1;
			
			System.out.println(fn);
			f0 = f1;
			f1 = fn;
			
			System.out.println(f0 + " + " + f1 + "Is");
		}
		
	}
	
}

·Execution result
f0= 0
f1= 1
1
1 +1 is
2
1 +2 is
3
2 +3 is
5
3 +5 is
8
5 +8 is
13
8 +13 is
21
13 +21 is
34
21 +34 is
55
34 +55 is
89
55 +89 is
144
89 +144 is
233
144 +233 is
377
233 +377 is
610
377 +610 is
987
610 +987 is
1597
987 +1597 is
2584
1597 +2584 is
4181
2584 +4181 is
6765
4181 +6765 is

The value is assigned to the variable fn and output as equal to the calculation result (f0) of the previous calculation + the previous calculation result (f1).

Recommended Posts

A rudimentary note on the Fibonacci sequence
A note on the libGDX Utils class
A note about the scope
A note about the seed function of Ruby on Rails
Note on the path of request.getRequestDispatcher
A review note for the class java.util.Scanner
A review note for the class java.util.Optional
A review note for the class java.util.Objects
A review note for the package java.time.temporal
A note on the differences between interfaces and abstract classes in Java
Come out with a suffix on the method
A note when the heroku command becomes unavailable
A note about the Rails and Vue process
A quick note on using jshell with the official Docker image of the JDK
I read the readable code, so make a note
A note for Initializing Fields in the Java tutorial
I wrote a sequence diagram of the j.u.c.Flow sample
A review note of the Spring Framework Resource interface
I tried JAX-RS and made a note of the procedure
Try launching a webAP server on the micro using Helidon
Use the high-performance SQL development tool "A5: SQL Mk-2" on Ubuntu