高精度加法

GitHub跳转原题关系图返回列表

利用 Python 任意精度整数,直接读入两个大整数后相加输出。

OJ: luogu

题目 ID: P1601

难度:入门

标签:高精度数学python

日期: 2026-07-15 21:35

题意

输入两个不超过 1050010^{500} 的非负整数,输出它们的和。

思路

在 C++ 中,这通常需要手写高精度加法。但 Python 的 int 是任意精度整数,可以直接保存远大于 long long 的整数。

所以本题 Python 解法就是:

  1. int(input()) 读入两个大整数;
  2. 输出 a + b

这题的教学目标是认识 Python 大整数,不创建 brute.py

Python 知识

  • /home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:Python 的 int 不会按 64 位整数溢出。
  • /home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:单行整数输入用 int(input())
  • 对大整数做 + 运算时,Python 会自动处理进位。

代码

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 = 505;

char a_str[MAXLEN], b_str[MAXLEN];
int  a_int[MAXLEN], b_int[MAXLEN]; // 逆序存储的数字,a_int[0] 是个位
int  res[MAXLEN];                  // 加法结果

// 把数字字符串 s 逆序存入数组 arr,返回位数
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_int[0..lena-1] + b_int[0..lenb-1] => res[0..]
int big_add(int *a, int lena, int *b, int lenb) {
    int carry = 0; // 进位
    int max_len = max(lena, lenb);
    for (int i = 0; i < max_len; i++) {
        int sum = carry;
        if (i < lena) sum += a[i];
        if (i < lenb) sum += b[i];
        res[i] = sum % 10; // 当前位
        carry = sum / 10;  // 进位
    }
    if (carry) {          // 如果最高位还有进位
        res[max_len] = carry;
        return max_len + 1;
    }
    return max_len;
}

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_add(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,大整数加法时间复杂度是 O(L)O(L),空间复杂度是 O(L)O(L)

总结

Python 写高精度模板题时,可以先直接使用内置 int。学习重点是知道它的优势和复杂度,而不是手写进位。