利用 Python 任意精度整数,直接读入两个大整数后相乘输出。
OJ: luogu
题目 ID: P1303
难度:入门
标签:高精度数学python
日期: 2026-07-15 21:35
题意
输入两个不超过
思路
Python 的 int 支持任意精度整数,可以直接完成高精度乘法:
python
print(a * b)这和 C++ 手写竖式乘法不同,Python 内置整数已经实现了大数运算。本文重点是学习 Python OJ 中如何利用语言特性,不创建 brute.py。
Python 知识
/home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:Python 整数不会溢出,适合处理高精度模板题。/home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:int(input())能直接解析很长的十进制整数。- 大整数乘法复杂度和位数有关,不是常数时间。
代码
python
a = int(input())
b = int(input())
print(a * b)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-07-27 00:00
* update_at: 2026-07-27 00:00
*/
#include <bits/stdc++.h>
using namespace std;
const int MAXLEN = 2005;
char a_str[MAXLEN], b_str[MAXLEN];
int a_int[MAXLEN], b_int[MAXLEN]; // 逆序存储
int res[MAXLEN * 2]; // 乘积最多 lena+lenb 位
// 字符串转逆序数字数组
int to_array(char *s, int *arr) {
int len = strlen(s);
for (int i = 0; i < len; i++)
arr[i] = s[len - 1 - i] - '0';
return len;
}
// 高精度乘法:a[0..lena-1] * b[0..lenb-1] => res[0..]
int big_mul(int *a, int lena, int *b, int lenb) {
// 每一位相乘
for (int i = 0; i < lena; i++) {
for (int j = 0; j < lenb; j++) {
res[i + j] += a[i] * b[j];
}
}
// 统一处理进位
int len_res = lena + lenb;
for (int i = 0; i < len_res; i++) {
if (res[i] >= 10) {
res[i + 1] += res[i] / 10; // 进位到高位
res[i] %= 10; // 保留个位
}
}
// 去掉前导 0
while (len_res > 1 && res[len_res - 1] == 0)
len_res--;
return len_res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> a_str >> b_str;
int lena = to_array(a_str, a_int);
int lenb = to_array(b_str, b_int);
int len_res = big_mul(a_int, lena, b_int, lenb);
for (int i = len_res - 1; i >= 0; i--)
cout << res[i];
cout << "\n";
return 0;
}Pythonic 写法
大整数乘法:
python
print(int(input()) * int(input()))复杂度
设数字位数为 L,大整数乘法由 Python 内部实现,复杂度随位数增长。对本题规模可以直接通过。
总结
在 Python 中,很多高精度整数题可以直接用内置 int。这是一种应当掌握的 OJ 语言优势。