【问题标题】:How do I multiply two big numbers if their digits are stored in two different arrays?如果两个大数的数字存储在两个不同的数组中,我如何将它们相乘?
【发布时间】:2020-05-06 15:51:14
【问题描述】:

我得到一个提示,可以通过标准乘法方法(使用 2d 数组)将它们相乘。但是谁能告诉我它是怎么做的?

到目前为止,这是我的代码,我不知道如何处理进位。我花了几个小时,最近才开始写代码。

    int main()
{
    int n, m, i, j;
    printf("Enter multiplicand(n) size: ");
    scanf("%d", &n);
    printf("Enter multiplier(m) size: ");
    scanf("%d", &m);
    int a[n], b[m];
    printf("Enter multiplicands: ");
    for(i = 0; i<n; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Enter multipliers: ");
    for(i = 0; i<m; i++)
    {
        scanf("%d", &b[i]);
    }

    int c[m][n+m];
    int k = 0 , l = m+n-1 , p = 2;
    for(i = 0; i<m; i++)
    {
        for(j = 0; j<m+n; j++)
        {
            c[i][j] = 0;
        }
    }
    for(i = m-1; i>=0; i--)
    {
        for(j = n-1; j>=0; j--)
        {
            if(a[j]*b[i] < 10)
            {
                c[k][l] = a[j]*b[i] + carry;
                l--;
            }
            else
            {
                carry = a[j]*b[i]%10;
                c[k][l] = carry;
            }
        }
        l = m+n-p;
        p++;
        k++;
    }
    for(i = 0; i<m; i++)
    {
        for(j = 0; j<m+n; j++)
        {
            printf("%d ", c[i][j]);
        }
        printf("\n");
    }
}

【问题讨论】:

  • 想象一下您将如何用铅笔和纸手工完成。现在在代码中执行此操作。
  • 抱歉,我试过了,但不知道如何编码。
  • 一般来说,您的问题应该集中在您的代码中的特定问题上。不幸的是,您还没有发布您的代码。对于此类问题,建议发布 minimal reproducible example 显示您尝试过的内容以及为什么它没有按照您的意愿/预期进行
  • 我投票结束这个问题,因为它表明 OP 没有为解决问题付出任何努力。

标签: c arrays multidimensional-array product multiplication


【解决方案1】:

阅读bignums 上的维基百科页面,然后阅读相关的会议论文。您可以获得博士学位以改进它们的乘法技术。这reportthat 之一(和许多其他)应该会让您感兴趣。

然后,研究一些开源bignum库的源码,比如GMPlib

更好的是,只需在您的 C 程序中使用该库(或其他一些 bignum 库,请参阅 this list)。

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多