从小到大枚举进制 B(2~40),检查三个数的每一位数字是否合法并用 Horner 展开求值,第一个满足 p×q=r 的 B 即答案。
OJ: roj
题目 ID: 1413
难度:入门
标签:枚举进制
创建: 2026-09-30 09:24
更新: 2026-10-05 23:14
题目描述
给定三个数字串
思路
从小到大枚举
参考代码
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 09:24
# update_at: 2026-09-30 09:24
import sys
B_MAX = 40 # 进制 B 的枚举上界(含)
def to_base(s: str, base: int) -> int:
"""把数字串 s 当作 base 进制转成十进制;出现非法数字则返回 -1。"""
value = 0
for ch in s:
digit = ord(ch) - ord('0')
if digit >= base: # 某一位数字超出进制允许范围,非法
return -1
value = value * base + digit
return value
def solve() -> None:
p, q, r = sys.stdin.read().split()
# 从小到大枚举进制,第一个满足 p*q=r 的就是答案
ans = next(
(
base
for base in range(2, B_MAX + 1)
if (x := to_base(p, base)) > 0
and x * to_base(q, base) == to_base(r, base)
),
0, # 没有任何进制合法
)
print(ans)
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 23:14
* update_at: 2026-10-05 23:14
*/
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
string p, q, r;
// 把数字串 s 当作 base 进制转成十进制;出现非法数字则返回 -1
ll to_base(const string &s, int base) {
ll value = 0;
for (char ch : s) {
int digit = ch - '0';
if (digit >= base) return -1; // 某一位数字超出进制允许范围,非法
value = value * base + digit;
}
return value;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> p >> q >> r;
for (int base = 2; base <= 40; ++base) {
ll pv = to_base(p, base);
ll qv = to_base(q, base);
ll rv = to_base(r, base);
if (pv >= 0 && qv >= 0 && rv >= 0 && pv * qv == rv) {
cout << base << '\n';
return 0;
}
}
cout << 0 << '\n';
return 0;
}