公式推导
代码实现:快速幂+费马小定理
快速幂概念及实现
import java.util.Scanner;
public class kuaisumi {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//输入两个参数计算幂
int a = sc.nextInt();//底数
int b = sc.nextInt();//指数
int temp, ans=1;
temp = a;
while(b!=0){
if(b%2==1){
ans = ans * temp;
}
b = b/2;
temp = temp*temp;
}
System.out.println(ans);
}
}
问题一:怎么加入费马小定理
问题二:数太大了怎么办
用BigInteger
//全题代码
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
BigInteger mod = new BigInteger("1000000007");
BigInteger three = new BigInteger("3");
BigInteger threeModMinusOne = three.multiply(mod).subtract(BigInteger.ONE);
BigInteger threeMod = three.multiply(mod); // 3 * mod
while (scan.hasNext()) {
BigInteger n = scan.nextBigInteger();
// System.out.println(n);
BigInteger c;
if (n.mod(BigInteger.TWO).equals(BigInteger.ONE)) {
c = new BigInteger("2");
} else {
c = new BigInteger("4");
}
BigInteger b = n.add(BigInteger.ONE).mod(threeModMinusOne);
BigInteger temp = new BigInteger("2");
BigInteger ans = BigInteger.ONE;
while (!b.equals(BigInteger.ZERO)) {
if (b.mod(BigInteger.TWO).equals(BigInteger.ONE)) {
ans = ans.multiply(temp).mod(threeMod);
}
b = b.divide(BigInteger.TWO);
// System.out.println(b);
// System.out.println(ans);
// System.out.println(temp);
temp = temp.multiply(temp).mod(threeMod);
}
BigInteger d = ans.mod(threeMod);
System.out.println(d);
BigInteger sum;
if (d.compareTo(c) >= 0) {
sum = d.subtract(c).divide(three);
} else {
sum = d.add(threeMod).subtract(c).divide(three);
}
System.out.println(sum);
}
scan.close();
}
}