import java.util.*;
public class FibonacciHuge {
static long get_pisano_period(long m){
long a=0,b=1,c=(a+b);
long res=0;
for(long i=0;i<m*m;i++) {
c = (a + b) % m;
a = b;
b = c;
if (a == 0 && b == 1) {
res = i + 1;
break;
}
}
return res;
}
static long fun(long n,long m){
long res=get_pisano_period(m);
n=n%res;
long cur=1;
long pre=0;
if(n==0)
return 0;
else if(n==1)
return 1;
System.out.println("pre"+n);
for(long i=0;i<=n-1;i++){
pre=cur;
cur=pre+cur;
System.out.println(pre+" "+cur); //debugging
}
return cur%m;
}
public static void main(String args[]){
long n,m;
Scanner sc=new Scanner(System.in);
n=sc.nextLong();
m=sc.nextLong();
System.out.println(fun(n,m));
}
}
这是我编写的使用pisano周期查找Fn%m的代码。但是问题是,在计算斐波那契数时,long的大小无法容纳该值:
对于输入n = 239 m = 1000
\\\ouptut
144115188075855872 288230376151711744
-9223372036854775808 0