Good evening. I have written the code counting the Fibonacchi numbers remainder by its number n by modulo m, but it turned out to give me negative remainders after n=100000, before that everything is fine. Before using Long, I used BigInteger instead: however, the code with such variable type is extremely slow.I also use Q-matrices and exponentiation by squaring. Here's the code:
import java.util.Scanner;
class Main {
private void bigfib(){
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long m = sc.nextLong();
long [][] a = new long[][]{{1,1},{1,0}};
System.out.println(pow(a,n)[0][1]%m);
}
private long[][] mult(long[][] m1, long[][] m2) {
long a11 = m1[0][0]*m2[0][0] + m1[0][1]*m2[1][0];
long a12 = m1[0][0]*m2[0][1] + m1[0][1]*m2[1][1];
long a21 = m1[1][0]*m2[0][0] + m1[1][1]*m2[1][0];
long a22 = m1[1][0]*m2[0][1] + m1[1][1]*m2[1][1];
long[][] mResult = new long[][]{{a11,a12},{a21,a22}};
return mResult;
}
private long [][] pow(long a[][], long p) {
long[][] result;
if (p==1)
return a;
if (p==2)
return mult(a,a);
if (p%2==1){
return mult(a,pow(a,p-1));
}
else{
result = pow(a,p/2);
return mult(result,result);
}
}
public static void main(String[] args) {
new Main().bigfib();
}
}
Could someone please tell me, why remainders start to be negative and how can that be fixed without BigItegers?