2025 / 11 / 25 开始学习快速幂
幂的定义
的 次方( 次幂)就是 个 相乘
写作: 读作:特殊的 当 时,可以读作“平方”。当 时,可以读作“立方”。
读作: 的 次方。
意义
比普通求幂快得多。
快速幂
板子…
一个求快速幂的函数:
typedef long long ll;
ll quickpow(ll n, ll m)
{
ll cnt = 1;
while (m)
{
if (m & 1)
cnt *= n;
n *= n;
m >>= 1;
}
return cnt;
}完整模板:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll quickpow(ll n, ll m)
{
ll cnt = 1;
while (m)
{
if (m & 1)
cnt *= n;
n *= n;
m >>= 1;
}
return cnt;
}
int32_t main()
{
cin.tie(nullptr)->ios::sync_with_stdio(false);
cout.tie(nullptr)->ios::sync_with_stdio(false);
ll n, m;
cin >> n >> m;
cout << quickpow(n, m);
return ~~(0-0);
}例题
ACwing:
洛谷:
例题 / 题解
ACwing
3625. 幂次方 / Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 233333;
ll quickpow(ll a, ll k)
{
ll cnt = 1;
while (k)
{
if (k & 1)
cnt = cnt * a % MOD;
a = a * a % MOD;
k >>= 1;
}
return cnt % MOD;
}
int32_t main()
{
cin.tie(nullptr)->ios::sync_with_stdio(false);
cout.tie(nullptr)->ios::sync_with_stdio(false);
ll x, n;
cin >> x >> n;
cout << quickpow(x, n);
return ~~(0-0);
}5579. 增加模数 / Code
#include<bits/stdc++.h>
using namespace std;
int T, x, h;
int quickpow(int n, int m)
{
int cnt = 1;
n %= x;
while (m)
{
if (m & 1)
cnt = cnt * n % x;
n = n * n % x;
m >>= 1;
}
return cnt;
}
int32_t main()
{
cin.tie(nullptr)->ios::sync_with_stdio(false);
cout.tie(nullptr)->ios::sync_with_stdio(false);
cin >> T;
while(T--)
{
int s = 0;
cin >> x >> h;
while(h--)
{
int a, b;
cin >> a >> b;
s = (s + quickpow(a, b)) % x;
}
cout << s << '\n';
}
return 0;
}