0x01--位运算
程序员文章站
2024-03-19 11:43:10
...
例题1:AcWing 89—a^b
快速幂取模运算标准模板,要熟练
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
long p = sc.nextLong();
sc.close();
long res = power(a, b, p);
System.out.println(res);
}
private static long power(long a, long b, long p) {
long res = 1 % p;
while(b > 0) {
if((b & 1) == 1) res = (res * a) % p;//b的最后一位是1
a = (a * a) % p;
b >>= 1;
}
return res;
}
}
例题2:AcWing 90–64位整数乘法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
long p = sc.nextLong();
sc.close();
long res = power(a, b, p);
System.out.println(res);
}
private static long power(long a, long b, long p) {
long res = 0;
while(b > 0) {
if((b & 1) == 1) res = (res + a) % p;//b的最后一位是1
a = (a * 2) % p;
b >>= 1;
}
return res;
}
}