0

We have a question for university to program a basic calculator but it would work with arbitrary integers. I have managed to get over addition and subtraction, but I do not really see how can I multiply 2 numbers when both are arbitrarily long. Currently using c language and I have been using pointers as character arrays. Any help would be very welcome...

    void sum(char*a, char*b)
{
    //initializing values
    int c,d,i;
    int carry=0;
    char *r;
    // counting the digits
    c=strlen(a);
    d=strlen(b);
    // checking which array is longer
    if (c>=d)
    {
        // if first array is longer we allocate enough memory for the result
        r=(char*)malloc((c+1)*sizeof(char));
        // incrementing backwards so we skip reversing the digits
        for (i=0; i<=d; ++i)
            {
                // mod 10 to extract only the last digit of the sum
                // that becomes our new digit
            *(r+c-i)=(*(a+c-i)+*(b+d-i)+carry)%10;
            carry=(*(a+c-i)+*(b+d-i))/10;
            }
            // copying the rest of the digits
        for (i=d+1; i<=c; ++i)
            *(r+c-i)=*(a+c-i);

    }
    //case when the other number has more digits
    else
    {
         r=(char*)malloc((d+1)*sizeof(char));
        for (i=0; i<=c; ++i)
            {
            *(r+d-i)=(*(a+c-i)+*(b+d-i)+carry)%10;
            carry=(*(a+c-i)+*(b+d-i))/10;
            }
        for (i=c+1; i<=d; ++i)
            *(r+d-i)=*(b+d-i);
    }
    // printing the result
    printf("The result is \n %s \n", r);
}

This is my code for addition so maybe that can give more insight into the problem, and how I am approaching it.

  • 6
    What have you tried so far? – Abhishek Nov 15 '20 at 20:35
  • 1
    Recall how you did it in elementary school, with pencil and paper, two digits at a time. [In case you forgot](https://en.wikipedia.org/wiki/Multiplication_algorithm#Long_multiplication) – Igor Tandetnik Nov 15 '20 at 20:36
  • This might help: https://stackoverflow.com/questions/24303813/number-of-digits-after-multiplication-dividing – Lukas-T Nov 15 '20 at 20:39
  • Multiplying one digit string by a single digit of the other string isn't so *very* different from adding two strings. Form those partial products and add each of them (aligned) to a product array. – Weather Vane Nov 15 '20 at 20:41
  • I have edited question, so maybe now you can understand better what i have been trying to ask. Thank you for pointing out my mistakes in the first question. – Pavle Stupar Nov 20 '20 at 19:34

0 Answers0