Fork me on GitHub

大数加法与乘法(数学巧算)

>
>

在这里介绍一种巧算的方法,核心代码只有六行!

大数加法(数学巧算)

//int a1[]为较长的数,int a2为较短的数
for(int i = 0;i<strlen(a1);i++)
{
    int temp1 = a1[i] + a2;
    a1[i] = temp1 % 10;
    a2 /= 10;
}

大数乘法(数学巧算)

//a1[],a2同上
for(int i = 0;i<strlen(a1);i++)
{
    int temp2 = a1[i] * a2 + temp2;
    a1[i] = temp2 % 10;
    temp2 /= 10; 
}

感觉很凝炼有木有

在加法中,

① 是将大数拆分成若干个元素,即数组元素,

② 从个位开始,让元素去加上较小的那个数,

③ 然后对它取模就是结果数的个位数,以此类推,

巧算之处在于,②中就已经将carryBit加到了a2中,省去了繁琐的新开变量来判断是否要进位

乘法也是相似的原理

大爱Java老师♥

Adhere to original technology sharing, your support will encourage me to continue to create!