C Program to Handle Large Numbers
The below example demonstrates the use of arrays to handle large numbers in 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.
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