Java implements the method of Fibonacci sequence based on high precision integer
- 2020-04-01 03:29:33
- OfStack
This article is an example of how to implement Fibonacci sequence in Java based on high precision integer. Specific methods are as follows:
package com.java.learning.recursion;
import java.math.*;
public class MainClass {
public static void main(String args[]){
for(int i = 0; i < 100; i++){
f(i+1);
}
}
public static BigInteger f(long n){
if(n <= 2){
return new BigInteger("1");
}else{
BigInteger n1 = new BigInteger("1");
BigInteger n2 = new BigInteger("1");
BigInteger temp = new BigInteger("0");
for(long i = 0; i < n -2; i++){
temp = n1.add(n2);
n1 = n2;
n2 = temp;
}
System.out.println(" The first " + n + " Items as follows: " + n2);
return n2;
}
}
}
I hope this article has been helpful to your Java programming.