Algorithm subsection (i)--Fibonacci sequence (Java implementation)

Source: Internet
Author: User

See the company's written test questions to write the Fibonacci sequence, I wrote a bit of a sneak

What is a Fibonacci sequence: The Fibonacci sequence refers to a sequence of 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 This sequence begins with the second item, each of which equals the sum of the first two.

in particular, the No. 0 item is 0, and the 1th item is the first 1. Note: At this time a1=1,a2=1,an=a (n-1) +a (n-2) (n>=3,n∈n*)Code:/**
* Created by Zhangjianchao
*/
public class Testalgorithm {
public static void Main (string[] args) {
Fibonacii fibonacii = new Fibonacii ();
System.out.println ("Final times =" +fibonacii.fibonacii (9));
}

}

Class fibonacii{
Public long Fibonacii (long N) {
int fn1 = 1; Item N-1
int fn2 = 1; Item N-2
INT fn = 0; Item n
The first two items of the IF (n<=2) {//series are 1
return 1;
}
Calculates the nth item, while recalculating the first n-2 and n-1 items
for (int i = 0;i < n-2;i++) {
fn = fn1 + fn2;
FN2 = fn1;
FN1 = fn;
System.out.println ("First" + i + "times fn (" + fn + ") = Fn1 (" + fn1 + ") + fn2 (" + fn2 + ")");
}
return FN;
}
}

Algorithm subsection (i)--Fibonacci sequence (Java implementation)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.