3 methods of implementing Fibonacci sequence in Java _java

Source: Internet
Author: User
Tags int size

First say why write this, this is entirely by the Alibaba interview caused by a miserable eye to see the murders. When I went to the interview, it was not until 11 o'clock the night before the interview that Alibaba appointed the interview city. Find a hotel to live under the basic is more than 1 o'clock, plus the night completely did not sleep well, directly resulting in the second day of the interview effect is very bad (for those who are looking for work of the prawns do not to shrimp a tragedy, prepared in advance or very important drop), The interview has been going on for about one hours (when the interview is over, the basic walk is fast asleep, sad urge!!) At the end of the interview, the interviewer asked me the question is about Fibonacci that the West series, when the mind is completely paste, only know to set three variables or first initialized with the list, when writing for the loop, the head is simply paste can not paste, did not write out, Finally, the interviewer's step-by-step guidance to write the following first way, it's not supposed to be. From now on, Ali just put the whole application framework set up, really change, digging gold golden period (the ability of the prawns hurriedly go), after all, Alibaba hands 99% Data are important data and to Baidu such as the main push search giant 99% data is garbage compared to for data analysis, Ali more through the hands of a variety of user detailed data analysis, more accurate positioning of the user's taste and demand for precision push and precision advertising push to provide better services. If the future of Tencent's dream is to do the user's life in the water and electricity, that Ali may realize the future of the dream is the user's basic necessities and the collection of water and electricity and so on, O (∩_∩) o~ or turn to the topic.
For a good algorithm designer, in the implementation of the program functional main body is nothing but care about two things, a design algorithm time complexity, one is the space complexity (plainly is to execute a program of time and Occupy memory space); On the basis of different application scenarios, Generally intelligent algorithm designers will be in time and space two of relatively contradictory resources to find the balance point, such as real-time requirements of the system will generally be in exchange for space resources for time or for commonly used objects generally resident memory to improve response time ( Caching technology and now more popular NoSQL is mostly memory database is the case, for memory resources of the more valuable embedded system in general will be time delay in exchange for time.
The following from the Fibonacci three implementation of the western series to say how to really design a real practical application of the best algorithm
First of all, Fibonacci, the western series:
According to the text, the Fibonacci series begins with 0 and 1, and the Faiponasi coefficients are added by the preceding two numbers, and the sequence forms as follows:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, .....
Mathematically, it is defined in a recursive way:
F_0=0
F_1=1
F_n = f_{n-1}+ F_{n-2}

Implementation requirements: Input ordinal n return to get corresponding Fibonacci that West number
Program realizes 1--function self-iteration

Copy Code code as follows:

/**
* Function Self Iteration
* @Title: FnType1
* @Description: TODO
* @param @param n
* @param @return
* @return int
* @throws Exception
*/
public int fnType1 (int n) throws exception{
if (n==0) {
return 0;
}else if (n==1| | n==2) {
return 1;
}else if (n>2) {
int Temp=fntype1 (n-1) +fntype1 (n-2);
if (temp<0) {
throw new Exception ("Invalid value for int type, too larage");
}else{
return temp;
}
}else{
throw new Exception ("Illegalargument value for N,please enter N>=0");
}
}

Disadvantages of this approach: a large number of iterations continue to consume stack space (for Web development debugging maintenance should know the value of the server stack resources, if a large number of concurrent calls to the iteration causes the server stack resources are not recycled, resulting in the Web server crashes), the efficiency of the end, the function of a weak Excellent interface should be the input and output error information can be captured, and provide clear results of processing, it is easy to error, debugging difficulties, in practical applications generally do not recommend this method, the use of the number of iterations can not be more than 3 times;
Program realizes 2--time changing space

Copy Code code as follows:

/**
* Time to change space
* @Title: FnType2
* @Description: TODO
* @param @param n
* @param @return
* @return Int (n<0 return-1,beyond max int size return-2)
* @throws
*/
public int fnType2 (int n) {
int result=-1;
int temp1=0;
int temp2=1;
for (int index=0;index<=n;index++) {
if (index==0) {
RESULT=TEMP1;
}else if (index==1) {
RESULT=TEMP2;
}else{
RESULT=TEMP1+TEMP2;
if (result<0) {
Result=-2;
Break
}
TEMP1=TEMP2;
Temp2=result;
}
}
return result;
}

This method is mainly used for: Use scene one: for objects or variables less frequently used, use a later will no longer use the scene; Use scenario two: for memory resources are scarce real-time requirements are not too high in embedded system design will use this way;
Program realizes 3--space in exchange for time

Copy Code code as follows:

private static list<integer> fndata=new arraylist<integer> ();
private static final int maxsize=50000;
/**
* Initialization of the device
* @Title: Setfndata
* @Description: TODO
* @param
* @return void
* @throws
*/
private static void Setfndata () {
int result=-1;
int temp1=0;
int temp2=1;
for (int index=0;index<=maxsize;index++) {
if (index==0) {
RESULT=TEMP1;
}else if (index==1) {
RESULT=TEMP2;
}else{
RESULT=TEMP1+TEMP2;
if (result<0) {
Result=-2;
Break
}
TEMP1=TEMP2;
Temp2=result;
}
Fndata.add (result);
}
}
/**
* External interface
* @Title: Getfndata
* @Description: TODO
* @param @param n
* @param @return
* @return int <span style= "FONT-FAMILY:SANS-SERIF;" > (n Beyond Fndata.size () and n<0 return-1) </span>
* @throws
*/
public int Getfndata (int n) {
if (Fndata.size () ==0) {
Setfndata ();
}
if (Fndata.size () >n&&n>=0) {
return Fndata.get (n);
}else{
return-1;
}
}

This method is commonly used for scenarios where an object or variable exists or is frequently invoked throughout the life cycle of a program, such as invoking an external WebService interface, an abstract persistence layer, a common profile parameter loading, and so on
Test Cases:

Copy Code code as follows:

Package com.dbc.yangg.swing.test;

Import java.util.ArrayList;
Import java.util.List;

/**
* Input ordinal n return to get corresponding Fibonacci that West number
* @ClassName: Init
* @Description: TODO
* @author guoyang2011@gmail.com
* @date January 10, 2014 7:52:13
*
*/
public class Init {
/**
* Function Self Iteration
* @Title: FnType1
* @Description: TODO
* @param @param n
* @param @return
* @return int
* @throws Exception
*/
public int fnType1 (int n) throws exception{
if (n==0) {
return 0;
}else if (n==1| | n==2) {
return 1;
}else if (n>2) {
int Temp=fntype1 (n-1) +fntype1 (n-2);
if (temp<0) {
throw new Exception ("Invalid value for int type, too larage");
}else{
return temp;
}
}else{
throw new Exception ("Illegalargument value for N,please enter N>=0");
}
}
/**
* Time to change space
* @Title: FnType2
* @Description: TODO
* @param @param n
* @param @return
* @return Int (n<0 return-1,beyond max int size return-2)
* @throws
*/
public int fnType2 (int n) {
int result=-1;
int temp1=0;
int temp2=1;
for (int index=0;index<=n;index++) {
if (index==0) {
RESULT=TEMP1;
}else if (index==1) {
RESULT=TEMP2;
}else{
RESULT=TEMP1+TEMP2;
if (result<0) {
Result=-2;
Break
}
TEMP1=TEMP2;
Temp2=result;
}
}
return result;
}
private static list<integer> fndata=new arraylist<integer> ();
private static final int maxsize=50000;
/**
* Space Change Time
* @Title: Setfndata
* @Description: TODO
* @param
* @return void
* @throws
*/
private static void Setfndata () {
int result=-1;
int temp1=0;
int temp2=1;
for (int index=0;index<=maxsize;index++) {
if (index==0) {
RESULT=TEMP1;
}else if (index==1) {
RESULT=TEMP2;
}else{
RESULT=TEMP1+TEMP2;
if (result<0) {
Result=-2;
Break
}
TEMP1=TEMP2;
Temp2=result;
}
Fndata.add (result);
}
}
/**
*
* @Title: Getfndata
* @Description: TODO
* @param @param n
* @param @return
* @return Int (n Beyond Fndata.size () and n<0 return-1)
* @throws
*/
public int Getfndata (int n) {
if (Fndata.size () ==0) {
Setfndata ();
}
if (Fndata.size () >n&&n>=0) {
return Fndata.get (n);
}else{
return-1;
}
}
/**
*
* @Title: Main
* @Description: TODO
* @param @param argv
* @return void
* @throws
*/
public static void Main (string[] argv) {
Init init=new init ();
int n=46;
try {
System.out.println ("type1=" +init.fntype1 (n));
catch (Exception e) {
TODO auto-generated Catch block
System.out.println (E.getmessage ());
}
System.out.println ("type2=" +init.fntype2 (n));
System.out.println ("type3=" +init.getfndata (n));
}
}

Output results:

Copy Code code as follows:

type1=1836311903
type2=1836311903
type3=1836311903

For algorithmic design, do not blindly follow the concept, the concept is dead, people are alive (in this need to crazy man's era, there are ideas than the rules more advantages), only with a specific application scenario to design a good algorithm and structure.
Spit: The individual thinks that the excellent data structure design can simplify the complexity of the algorithm design, improve the readability of the code, the extension of the program and the execution efficiency;
And then spit: do demand analysis should follow the three point principle: 1. From the user perspective and the way of thinking; 2. The user is not necessarily what they really want; 3. The user is not necessarily right to say. Follow the principles of program development: actively enhance their own taste, standing in the user perspective and the use of scene analysis functions; for example, you do background interface development, your user is the interface caller, you should consider what the interface function is, users in what circumstances will call, incoming parameters may cause which exceptions, What exceptions might appear in your interface implementation and catch the exceptions that might occur. Clear output, good function of the autistic; If you're in front of the desk, you should design the UI from the user's usage habits, and so on, on the basis of your business implementation. It's interesting. No, the need, the development of more natural will understand O (∩_∩) o~.

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.