Home > Java > javaTutorial > body text

Java Example - Fibonacci Sequence

黄舟
Release: 2017-02-16 10:09:17
Original
1530 people have browsed it

The Fibonacci sequence refers to a sequence of numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368...

Specially pointed out: item 0 is 0, item 1 is the first 1.

This sequence starts with the third term, and each term is equal to the sum of the previous two terms.

The following example demonstrates the implementation of the Fibonacci sequence in Java:

/*
 author by w3cschool.cc
 MainClass.java
 */public class MainClass {
   public static long fibonacci(long number) {
      if ((number == 0) || (number == 1))
         return number;
      else
         return fibonacci(number - 1) + fibonacci(number - 2);
   }
   public static void main(String[] args) {
      for (int counter = 0; counter <= 10; counter++){
         System.out.printf("Fibonacci of %d is: %d\n",
         counter, fibonacci(counter));
      }
   }}
Copy after login

The output result of running the above code is:

Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55
Copy after login

The above is the Java example-Fibonacci sequence For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!