链接:https://ac.nowcoder.com/acm/contest/330/E
来源:牛客网
题目描述
精通程序设计的 Applese 叕写了一个游戏。
在这个游戏中,有一个 n 行 m 列的方阵。现在它要为这个方阵涂上黑白两种颜色。规定左右相邻两格的颜色不能相同。请你帮它统计一下有多少种涂色的方法。由于答案很大,你需要将答案对 109+7 取模。
输入描述:
仅一行两个正整数 n, m,表示方阵的大小。
输出描述:
输出一个正整数,表示方案数对 109+7 取模。
示例1
输入
1 1
输出
2
示例2
输入
2 2
输出
4
备注:
1≤n,m≤10100000
因为每行只有两种涂色可能,所以共有2的n次方种涂色方法
只记得用快速幂忘了用费马小定理了otz
费马小定理:a^x%p=a^(x%(p-1))%p.
所以先用费马小定理降幂再用快速幂才不会超时orz因为给出的数据范围是大数所以用了java(……)
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static long testPosition(Long a,BigInteger b) {
long mod=1000000007;
long s = 1;
BigInteger r=new BigInteger("0");
r=BigInteger.valueOf(2);
BigInteger h=new BigInteger("0");
while (b.compareTo(BigInteger.valueOf(0))>0) {
h=b.mod(r);
if (h.equals(BigInteger.valueOf(1))) {
s = s % mod;
a = a % mod;
s = s * a;
}
a = a % mod;
a = a * a;
b=b.divide(BigInteger.valueOf(2));
}
return s % mod;
}
public static void main(String[] args) {
long mod=1000000007;
BigInteger n=new BigInteger("0");
BigInteger m=new BigInteger("0");
Scanner cin=new Scanner(System.in);
n=cin.nextBigInteger();
n=n.mod(BigInteger.valueOf(mod-1));
long g=2;
System.out.println(testPosition(g,n));
}
}