{ }codelper
64 位整数溢出求和P0015

大数求和

第一行给出整数个数 n,第二行给出用空格分隔的 n 个整数。
输出它们的和。

输入
1 ≤ n ≤ 10,000,-1,000,000,000 ≤ 每个数 ≤ 1,000,000,000(每个数都能放进 32 位 int)
输出
一行和(在 -10^13 到 10^13 之间)
样例 1 · stdin
3
1000000000 1000000000 1000000000
stdout
3000000000
样例 2 · stdin
4
5 -2 7 -10
stdout
0
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

每个数都能放进 int(32 位,约 ±21 亿),但和放不下。
所以数可以用 int 读,但累加和的变量必须是 64 位:C/C++ long long(C 的 long 在 Windows 上是 32 位),Java/C# long。
用 int 会得到错误的数且没有任何报错——Java 和 C# 默认溢出时悄悄回绕(C# 用 checked 包起来会抛异常),C/C++ 中有符号整数溢出是未定义行为。
Python 整数没有大小限制;JS/TS/Craykon 只有一种双精度数字类型,在 2^53(约 9×10^15)以内精确,所以最大 10^13 的本题直接就行。

Pythonmain.py · 2 行
n = int(input())print(sum(map(int, input().split())))
JavaScriptmain.js · 3 行
const [n, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// 합은 최대 10^14 — 2^53(약 9×10^15)보다 작아서 Number로 정확하다console.log(a.reduce((s, x) => s + x, 0));
TypeScriptmain.ts · 3 行
import { readFileSync } from "node:fs";const [n, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(a.reduce((s, x) => s + x, 0));
JavaMain.java · 14 行
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        StringTokenizer st = new StringTokenizer(br.readLine());        long total = 0; // 수 하나는 int에 들어가도 합은 long이 필요하다        for (int i = 0; i < n; i++) total += Integer.parseInt(st.nextToken());        System.out.println(total);    }}
C#Main.cs · 13 行
using System; class Program{    static void Main()    {        Console.ReadLine();        long total = 0; // int로 두면 조용히 넘친다(C#은 기본이 unchecked)        foreach (string s in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries))            total += int.Parse(s);        Console.WriteLine(total);    }}
C++main.cpp · 14 行
#include <iostream> int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int n, x;    long long total = 0;    std::cin >> n;    for (int i = 0; i < n; i++) {        std::cin >> x;        total += x;    }    std::cout << total << '\n';}
Cmain.c · 13 行
#include <stdio.h> int main(void) {    int n, x;    long long total = 0; /* long은 Windows에서 32비트라 long long을 쓴다 */    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%d", &x);        total += x;    }    printf("%lld\n", total);    return 0;}
Craykonmain.cray · 8 行
n = 控制台.读行().转数字();수들 = 控制台.读数字();합 = 0;遍历 (x 在 수들){    합 += x;}控制台.输出(합);