参考代码
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
long n,m;
n=sc.nextLong();
m=sc.nextLong();
BigInteger p=sc.nextBigInteger(),fn,fm;
if(n+2>m)
{
fm=think(m,null);
fn=think(n+2,fm).subtract(new BigInteger("1"));
System.out.println(fn.remainder(fm).remainder(p));
}
else
{
fn=think(n+2,p).subtract(new BigInteger("1"));
System.out.println(fn.remainder(p));
}
}
private static BigInteger think(long m,BigInteger mod) {
// TODO Auto-generated method stub
BigInteger a1=new BigInteger("1"),a2=new BigInteger("1"),x[][];
if(m==1)return a1;
else if(m==2)return a2;
else
{
x=new BigInteger[2][2];
x[0][0]=new BigInteger("1");
x[0][1]=new BigInteger("1");
x[1][0]=new BigInteger("1");
x[1][1]=new BigInteger("0");
x=doublex(x,m-2,mod);
return x[0][0].add(x[0][1]);
}
}
private static BigInteger[][] doublex(BigInteger[][] x, long n,BigInteger mod) {
// TODO Auto-generated method stub
BigInteger x2[][];
x2=new BigInteger[2][2];
if(n==1)return x;
else
{
if(n%2==1)return cheng(doublex(cheng(x,x,mod),n/2,mod),x,mod);
else return doublex(cheng(x,x,mod),n/2,mod);
}
}
private static BigInteger[][] cheng(BigInteger[][] x, BigInteger[][] y,BigInteger mod) {
// TODO Auto-generated method stub
BigInteger z[][];
z=new BigInteger[2][2];
if(mod!=null)
{
z[0][0]=x[0][0].multiply(y[0][0]).add(x[1][0].multiply(y[0][1])).remainder(mod);
z[0][1]=x[0][0].multiply(y[0][1]).add(x[0][1].multiply(y[1][1])).remainder(mod);
z[1][0]=x[1][0].multiply(y[0][0]).add(x[1][1].multiply(y[1][0])).remainder(mod);
z[1][1]=x[1][0].multiply(y[0][1]).add(x[1][1].multiply(y[1][1])).remainder(mod);
return z;
}
z[0][0]=x[0][0].multiply(y[0][0]).add(x[1][0].multiply(y[0][1]));
z[0][1]=x[0][0].multiply(y[0][1]).add(x[0][1].multiply(y[1][1]));
z[1][0]=x[1][0].multiply(y[0][0]).add(x[1][1].multiply(y[1][0]));
z[1][1]=x[1][0].multiply(y[0][1]).add(x[1][1].multiply(y[1][1]));
return z;
}
}