简体   繁体   中英

Computer cannot store numbers with more than approximately 15 digits. Is there a way to do these sums in Python?

We want to perform addition for numbers with a large number of digits (for example, 100-digit numbers). Computer cannot store numbers with more than approximately 15 digits. Is there a way to do these sums? The output should be the sum of the numbers given in the input.

Input:

3

111111111111111

22222222

2323

Output:

111111133335656

This is a answer for java but I want it in python

import java.util.Scanner;

class Main {

static Scanner sc;
static String strInput;

public static void main(String[]args) {
    sc = new Scanner(System.in);

    int n = Integer.parseInt(sc.nextLine());

    if (n < 1 || n > 20)
        return;

    String[] inputNumbers = new String[n];

    int max_len = 0;

    for (int i = 1; i <= n; i++) {
        inputNumbers[i-1] = sc.nextLine();

        if(max_len < inputNumbers[i-1].length())
            max_len = inputNumbers[i-1].length();
    }

    String[][] myNumbers = new String[n][max_len];
    int j = 0;

    for (int i = 1; i <= n; i++) {
        for (j = 0; j < max_len; j++) {
            myNumbers[i-1][j] = "0";
        }
    }

    int temp_len = 0;
    for (int i = 1; i <= n; i++) {
        temp_len = inputNumbers[i-1].length();
        j = max_len - temp_len;
        for (char ch:inputNumbers[i-1].toCharArray()) {
            myNumbers[i-1][j] = String.valueOf(ch);
            j++;
        }
    }

    String sumNumbers = "";
    int sum = 0;
    int borrow = 0;

    for(j = max_len - 1; j >= 0; j--) {
        for (int i = 1; i <= n; i++) {
            sum += Integer.parseInt(myNumbers[i-1][j]);
        }

        sum += borrow;
        borrow = 0;

        if(sum > 9) {
            borrow = sum / 10;
            sum = sum - (borrow * 10);
        }

        sumNumbers = String.valueOf(sum) + sumNumbers;
        sum = 0;
    }

    if(borrow!=0) {
        max_len++;
        System.out.print(String.valueOf(borrow));
    }

    System.out.println(sumNumbers);

}

}

You are incorrect. All Python integers are arbitrary precision integers (similar to BigInt or BigNum) in other languages. Summing large numbers will work out if the box with no additional work needed.

There's no limit to the size of integer a computer can store beyond it's memory. Many languages use fixed size integers of a fixed number of bits (usually 32 or 64), and CPU operations are designed to operate on specific integer sizes (generally 64 bit). This means that for very large integers (more than 19 decimal digits, roughly) addition takes more than a single CPU operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM