How to Handle Large Numbers in C?

In C, the maximum value that an integer type variable can store is limited. For instance, the maximum value that an long long int can hold in 64-bit compiler is 9223372036854775807. So, how can we handle numbers that are larger than this? In this article, we will learn how to handle large numbers in C.

Example:

Input:
num1 = 12345678901234567890
num2 = 98765432109876543210

Output:
Sum: 111111111011111111100

Working with Big Numbers in C

To handle large numbers in C, we can use arrays or strings to store individual digits of the large number and perform operations on these digits as required. String them as strings can be beneficial as each digit only takes one byte we can use the inbuilt methods to work on it.

C Program to Handle Large Numbers

The below example demonstrates the use of arrays to handle large numbers in C.

C
// C program to handle large numbers
#include <stdio.h>
#include <string.h>

// Function to add two large numbers
void addLargeNumbers(char* num1, char* num2)
{
    int len1 = strlen(num1);
    int len2 = strlen(num2);
    int carry = 0;
    int i;

    // Make both numbers of equal length
    while (len1 < len2) {
        // Prepend zero in num1
        memmove(num1 + 1, num1, len1 + 1);
        num1[0] = '0';
        len1++;
    }
    while (len2 < len1) {
        // Prepend zero in num2
        memmove(num2 + 1, num2, len2 + 1);
        num2[0] = '0';
        len2++;
    }

    // Add digits from right to left
    for (i = len1 - 1; i >= 0; i--) {
        int digit
            = (num1[i] - '0') + (num2[i] - '0') + carry;
        num1[i] = (digit % 10) + '0';
        carry = digit / 10;
    }

    // If there is a carry after adding all digits
    if (carry) {
        memmove(num1 + 1, num1, len1 + 1);
        num1[0] = carry + '0';
    }
}

int main()
{
    char num1[100] = "9999999999999999999999999999999999999"
                     "9999999999999999999999999999999999999"
                     "99999999999999999999999999";
    char num2[100] = "1";

    addLargeNumbers(num1, num2);

    printf("Sum: %s\n", num1);

    return 0;
}

Output
Sum: 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Time Complexity: O(n), where n is the number of digits in the large number.
Auxiliary Space: O(n), where n is the number of digits in the large number.

We can add more operations for this kind of number representation to make it according to our needs.