Java mathematical induction is a non recursive method of finding the Fibonacci sequence
- 2020-04-01 04:00:47
- OfStack
This article illustrates the non-recursive method of Java mathematical induction to find the Fibonacci sequence. Share with you for your reference. The details are as follows:
Integer can represent a maximum of
2147483647
It's about 2.14 billion. We don't take overflow into account here (it will overflow when the size is 983)!
import java.util.List;
import java.util.ArrayList;
public class Fibonacci {
public static List<Integer> fibonacci(int size) throws Exception {
int first = 0;
int second = 1;
List<Integer> result = new ArrayList<Integer> ();
result.add(first);
result.add(second);
if(size < 0) {
throw new Exception("Illegal argument!");
}
else if(size <= 2) {
return result.subList(0, size);
}
int next;
int count = 2; //The number of elements that have been derived so far
while(count++ < size) { //Other elements are recursed based on fib(0) and fib(1)
next = first + second;
first = second;
second = next;
result.add(next);
}
return result;
}
public static void main(String[] args) throws Exception {
List<Integer> fibArray = fibonacci(10);
for(int i: fibArray) {
System.out.print(i + "t");
}
}
}
I hope this article has been helpful to your Java programming.