J'essaie d'exécuter un programme qui trouve la nième séquence dans la série Fibonacci; Cependant, le problème est, je veux implémenter BigInteger dedans afin qu'il puisse exécuter des valeurs de 1000 ou même plus.Java Fibonocci sequence BigInteger
Est-il possible de l'ajouter efficacement?
import java.util.*;
import java.math.*;
public class fib {
//Arkham
/*public static BigInteger fibonacci2(int n) {
if (n == 0 || n == 1) {
return BigInteger.ONE;
}
return fibonacci2(n - 2).add(fibonacci2(n-1));
}*/
public static int Fibonacci(int n) {
int num = Math.abs(n);
if (num == 0) {
return 0;
}
else if (num <= 2) {
return 1;
}
int[][] number = { { 1, 1 }, { 1, 0 } };
int[][] result = { { 1, 1 }, { 1, 0 } };
while (num > 0) {
if (num%2 == 1) result = MultiplyMatrix(result, number);
number = MultiplyMatrix(number, number);
num/= 2;
}
return result[1][1]*((n < 0) ? -1:1);
}
public static int[][] MultiplyMatrix(int[][] mat1, int[][] mat2) {
return new int[][] {
{ mat1[0][0]*mat2[0][0] + mat1[0][1]*mat2[1][0],
mat1[0][0]*mat2[0][1] + mat1[0][1]*mat2[1][1] },
{ mat1[1][0]*mat2[0][0] + mat1[1][1]*mat2[1][0],
mat1[1][0]*mat2[0][1] + mat1[1][1]*mat2[1][1] }
};
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt();
System.out.println("\n" + Fibonacci(n));
}
}
Quel est le problème avec l'utilisation 'BigInteger'? – Oleg
Idk comment l'implémenter, ou l'utiliser dans cette situation spécifique. quand je mets dans 100, je devrais obtenir 354224848179261915075 à la place je reçois -980107325 – ArkhamWarfare
Remplacer tout 'int' avec BigInteger' et tous les opérateurs avec des appels de méthode' Biginteger'. – Oleg