取 n 的末四位作为指数,用快速幂求 2011^n mod 10^4。
OJ: roj
题目 ID: 1234
难度:普及-
标签:数论快速幂python
创建: 2026-09-30 00:56
更新: 2026-10-07 12:15
题目描述
给定
思路
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-30 00:57
# update_at: 2026-09-30 00:57
import sys
MOD = 10000 # 只保留后四位
def solve() -> None:
data = iter(sys.stdin.buffer.read().split())
k = int(next(data)) # 数据组数
nums = list(data) # 每组一个指数串,位数可达 200
out: list[str] = []
for i in range(k):
# 个别测试点声明的 k 多于实际数字个数:对齐 std 的 cin>>string
# 在 EOF 处失败时字符串保持原值的行为,沿用上一个指数
n = nums[i] if i < len(nums) else nums[-1]
out.append(str(pow(2011, int(n[-4:]), MOD)))
print('\n'.join(out))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 06:12
* update_at: 2026-10-05 06:12
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll MOD = 10000; // 只保留后四位
const ll BASE = 2011; // 底数
// 快速幂:返回 base^e % mod
ll qpow(ll base, ll e, ll mod) {
ll res = 1 % mod;
ll a = base % mod;
while (e > 0) {
if (e & 1) res = res * a % mod;
a = a * a % mod;
e >>= 1;
}
return res;
}
// 取字符串最后至多 4 位对应的整数
ll last_four(const string &s) {
int len = s.length();
int start = max(0, len - 4);
ll val = 0;
for (int i = start; i < len; i++) {
val = val * 10 + (s[i] - '0');
}
return val;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int k;
if (!(cin >> k)) return 0;
string last_n, n;
for (int i = 0; i < k; i++) {
if (cin >> n) {
last_n = n; // 读成功则更新
}
// 读失败时 last_n 保持原值,对齐旧版 cin>>string 的失败语义
ll e = last_four(last_n);
cout << qpow(BASE, e, MOD) << "\n";
}
return 0;
}