Java implements three methods of the Fibonacci sequence

  • 2020-04-01 02:44:44
  • OfStack

First of all, why do you write this? This is totally caused by an interview in alibaba. Go to the interview, as a result of the interview at 11 o 'clock in the evening the day before yesterday didn't specify the interview city to alibaba, find a hotel stay basically more than 1 point, and did not sleep well at night, a direct result of the second day of the interview result is very bad (for those who are looking for a job the prawns are not to shrimp tragedy, get ready for your arrival or important drops), the interview probably for more than an hour (basic walking when the end of the interview back are fast asleep, miserable!!) , near the end of the interview the interviewer ask me questions about the west its sequence, when the mind is completely paste, only know to set up the three variables, or use the List to initialize, when write a for loop, head can't paste paste, didn't write, finally can only in the interviewer's induced by wrote the following first way step by step, so should not be; From now to see ali is the careless of the to build up the framework of the whole application, it's change, digging gold gold period prawn go (ability), alibaba, after all, 99% of the data are important data for this kind of baidu, the search giant, compared to 99% data are rubbish for data analysis, ali can by hand grasp a variety of more user data is analyzed in detail, more accurately locate the user's tastes and needs, to provide accurate push and precise advertising push a better service. If the future dream of tencent is to be the water and electricity in the life of users, then the future dream that ali may realize is the clothing, food, housing and transportation of users plus the collection of water and electricity, etc.
    For a good algorithm designer, on the basis of the realization of the main function of the program, there are only two things to be concerned about: the time complexity of the design algorithm and the space complexity (in other words, the time and memory space occupied by the execution of a program); In according to the different application scenarios, on the basis of general intelligent algorithm designers can in time and space of two relative contradiction seek to balance resources, such as high real-time demand system generally with the space resources in exchange for a time or to the commonly used to object usually resident in memory in order to improve the response time (cache technology and popular now no (mostly in the memory, both in the database, and memory resources are valuable for the embedded systems typically to because of the delay in time for the time.
The following three implementations of the Fibonacci sequence are described. How to truly design an excellent algorithm that is in line with the actual application scenarios
First, the Fibonacci sequence:
Literarily, the Fibonacci sequence starts with 0 and 1, and the subsequent Fibonacci coefficient is added by the previous two Numbers. The sequence form is 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 recursively:
F_0 = 0
F_1 = 1
F_n F_ = {}, n - 1 + F_ {2} n -

Implementation requirements: input sequence number n to return the corresponding Fibonacci number
Program implementation 1 - function self - iteration



 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 ");
  }
 } 

This way faults: a large number of iterations depleting stack space (make web development debug maintenance should know server stack resources value, if a large number of simultaneous calls iteration to stack the server resources, slow recovery, causes the web server crash), efficiency, function autistic weaker sex (excellent interface should to capture input/output error messages that may occur, and provide the clear processing result), very prone to error, debugging difficulty, generally do not recommend using this way, in the practical use when the number of iterations can't more than three times;
Program implementation 2 - time for space



 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 in: use scenario 1: for the object or variable used less times, after the use of one will not be used again; Use scenario 2: this method is often used in embedded system design where the real-time requirement of memory resources is not too high.
Program implementation 3 - space for time


 private static List<Integer> fnData=new ArrayList<Integer>();
 private static final int maxSize=50000;
 
 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 typically used in situations where an object or variable is present or invoked frequently throughout the life of a program, such as calling an external WebService interface, the abstraction persistence layer, common configuration file parameter loading, and so on
Test case:


package com.dbc.yangg.swing.test;
import java.util.ArrayList;
import java.util.List;

public class Init {
 
 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 ");
  }
 } 
 
 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;
 
 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);
  }
 }
 
 public int getFnData(int n){
  if(fnData.size()==0){
   setFnData();
  }
  if(fnData.size()>n&&n>=0){
   return fnData.get(n);
  }else{
   return -1;
  }
 }
 
 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:


Type1=1836311903  
Type2=1836311903  
Type3=1836311903  

For the algorithm design, don't blindly follow the concept, the concept is dead, the person is alive (in this era that requires crazy man, there are more advantages to have ideas than to follow the rules), only combined with specific application scenarios to design excellent algorithm and structure.
Make fun of it: I think excellent data structure design can simplify the complexity of algorithm design and improve the readability of code, expansibility and execution efficiency of program.
Make fun of it again: three principles should be followed when doing demand analysis: 1. Analyze from the perspective of users and their way of thinking; 2. 2. What users say may not be what they really want; 3. What the user says is not necessarily right. Do program development follow the principles: actively improve their own taste, stand in the user's perspective and use the scene analysis function; You do a backend interface development, for example, your user interface the caller, you should consider what is the function interface, users under what circumstances will call, the incoming parameters can lead to which exceptions, you may appear in the interface implementation of which exceptions and possible exception is caught, the output of the clear, good function autism; If you are a receptionist, you should design the UI as a user in terms of user habits and other aspects while ensuring the business implementation. It's interesting. Yes, if you have more requirements and more development, you will understand.


Related articles: