C Program to Multiply Large numbers

multiplication

C program to multiply large numbers has been shown here. This program follows the standard multiplication algorithm.




Page content(s):

1. Program & Output





1. C program & output to Multiply Large numbers

Code has been copied
/************************************
    	alphabetacoder.com
 C program to multiply large numbers
*************************************/

#include <stdio.h>
#include <string.h>
 //set maximum size of the input numbers
#define MAX 500

int main() {
    // declare varables
    char num1[MAX], num2[MAX]; // for storing large numbers.
    int result[2 * MAX] = {0};
    // for storing the result
    int n1, n2, d1, d2, i, j, sum, carry, flag = 0;

    // Read input numbers
    printf("Enter the first number: ");
    scanf("%s", num1);
    printf("Enter the second number: ");
    scanf("%s", num2);

    //find the number of digits for both numbers.
    n1 = strlen(num1);
    n2 = strlen(num2);

    // Perform multiplication
    // Multiply each digit of num1 with each digit of num2
    for (i = n1 - 1; i >= 0; i--) {
        // initialize
        carry = 0;
        d1 = num1[i] - '0'; // current digit of first number

        for (j = n2 - 1; j >= 0; j--) {
            d2 = num2[j] - '0'; // current digit of second number
            // calculate sum
            sum = d1 * d2 + result[i + j + 1] + carry;
            result[i + j + 1] = sum % 10;
            // calculate carry
            carry = sum / 10;
        }

        // Set the carry to the leading digit
        result[i] = carry;
    }

    // display the result
    // discard the leading 0s in result array
    printf("Result = ");
    for (i = 0; i < (n1 + n2); i++) {
        if (result[i])
            flag = 1;
        if (flag)
            printf("%d", result[i]);
    }

    return 0;
}

Output


Enter the first number: 47771324767464454646465446464688879878974321524857451254875414574512485754124854241578887445787454124857524524545248575454547451248754

Enter the second number: 988754545421215444123485445242415245420445576874135468724578448574657987443994654468745412122124545454878789934557467465465468757786778787878798

Result = 47234114504623567435933878704274485175842876541707331278804882463108053938314071233587846425511881735181565684398142342387514944066523585420570029814418573817692598464892531177169082116019030769201727589777768498535602041076351997994350183545944126849807797118519698443900517692