快速幂相关:
//求 mk%pmk%p ,时间复杂度 O(logk)O(logk)。
int qmi(int m, int k, int p)
{
int res = 1, t = m;
while (k)
{
if (k&1) res = res * t % p;
t = t * t % p;
k >>= 1;
}
return res;
}
1.Leetcode 372 Super Pow
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example 1:
Input: a = 2, b = [3]
Output: 8
Example 2:
Input: a = 2, b = [1,0]
Output: 1024
class Solution {
public static final int MOD = 1337;
public int qpow(int a,int n){
int res = 1;
a %= MOD;
while(n != 0){
if((n & 1 )== 1){
res = (res * a) % MOD;
}
a = (a * a) % MOD;
n >>= 1;
}
return res;
}
public int superPow(int a, int[] b) {
int ans = 1, len = b.length;
for (int i = 0; i < len; i ++) {
ans = (qpow(ans, 10) * qpow(a, b[i])) % MOD;
}
return ans;
}
}
2.Leetcode 50 Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
class Solution {
public:
double myPow(double x, int n) {
double ans = 1;
if(n > 0){
while(n){
if(n & 1){
ans *= x;
}
x *= x;
n >>= 1;
}
}else{
if(n == INT_MIN){
n = INT_MAX;
while(n){
if(n & 1){
ans *= x;
x *= x;
n >>= 1;
}
}
ans = abs(1.0/ans);
}else{
n *= -1;
while(n){
if(n & 1){
ans *= x;
}
x *= x;
n >>= 1;
}
ans = 1.0 / ans;
}
}
return ans;
}
};
3.Acwing 89 a^b
求 aa 的 bb 次方对 pp 取模的值。
输入格式
三个整数 a,b,pa,b,p ,在同一行用空格隔开。
输出格式
输出一个整数,表示a^b mod p
的值。
数据范围
1≤a,b,p≤1091≤a,b,p≤109
输入样例:
3 2 7
输出样例:
2
#include
using namespace std;
int main(){
int a,b,p;
cin >> a >> b >> p;
int res = 1 % p;
while(b){
if(b & 1){
res = res * 1ll * a % p;
}
a = a * 1ll * a % p;
b >>= 1;
}
cout << res << endl;
return 0;
}
4.Acwing 90 64位整数乘法
求 aa 乘 bb 对 pp 取模的值。
输入格式
第一行输入整数aa,第二行输入整数bb,第三行输入整数pp。
输出格式
输出一个整数,表示a*b mod p
的值。
数据范围
1≤a,b,p≤10181≤a,b,p≤1018
输入样例:
3 4 5
输出样例:
2
#include
using namespace std;
typedef unsigned long long ull;
int main(){
ull a,b,c;
cin >> a >> b >> c;
ull res = 0;
while(b){
if(b & 1){
res = (a + res) % c;
}
b >>= 1;
a = a * 2 % c;
}
cout << res << endl;
return 0;
}
import java.math.BigInteger;
import java.util.Scanner;
/**
* @Author:HowieLee
* @Date:1/15/2019
* @Description:Acwing
* @version:1.0
*/
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
String c = sc.next();
//String[] b = a.split(" ");
BigInteger a1 = new BigInteger(a);
BigInteger b1 = new BigInteger(b);
BigInteger c1 = new BigInteger(c);
a1 = a1.mod(c1);
b1 = b1.mod(c1);
System.out.println(a1.multiply(b1).mod(c1));
}
}
5.