跳到正文

生活·游记

【模板】快速幂

zhy_qs约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

2025 / 11 / 25 开始学习快速幂

幂的定义

nn 的 mm 次方(mm 次幂)就是 mm 个 nn 相乘

写作:nm   n^m\ \ \ 读作:特殊的 ⟶\longrightarrow 当 m=2m = 2 时,可以读作“平方”。当 m=3m = 3 时,可以读作“立方”。

eg. 24=2×2×2×2=16\text{eg.}\ 2^4 = 2 \times 2 \times 2 \times 2 = 16 读作:22 的 44 次方。

意义

比普通求幂快得多。

快速幂

板子…

一个求快速幂的函数:

C++
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;
}

完整模板:

C++
#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
C++
#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
C++
#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;
}

看哭全球十亿普通幂。看哭全球十亿普通幂。

——zhyzhy
原文