歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言實現大數乘法

C語言實現大數乘法

日期:2017/3/1 9:16:26   编辑:Linux編程

實現過程分析:

我們回憶一下,在我們小時候剛接觸多位數的乘法,我們的數學老師會教給我們一個方法,那就是“乘法的豎式計算”。在這裡我們就采用該思想解決大數乘法的問題。

以下是我們經常進行乘法的豎式運算:

根據以上的豎式運算,我們實現過程總結如下:

1、先使用兩個字符數組保存兩個大數據;

2、用第一個數據的個位與第二個數據的所有位相乘,並將每一位的運算結果保存在暫存字符數組temp中,並進行進位調整,即如果該位的數值大於9,就將該數值的十位加到前一位,並將該位的個位保存在原位。

3、將temp與結果數組rst中的數值逆序相加,也就是從兩個數組的倒數第一位開始相加。

4、以相同的方法,計算出第一個數據的十位與第二個數據相乘的結果,並保存至temp中。

5、將temp與rst倒數第二位的結果開始逆序相加。

6、第一個數據有幾位就將以上過程進行幾次。

注:對於確定每次與rst的倒數第幾位相加時,可以采用一個bit變量存下正在進行第一個數據的第幾位數據的運算,在最終相加時,在rst數組的末尾減去bit就是,應該與temp最後一位相加的位數。

C語言實現過程:

OK! 我們可以帶著對這個乘法豎式的重新理解來解決我們的大數乘法問題,以下是C語言實現的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN (100)
#define RSTMAX (1000000)

int main(int ac, char **av)
{
char Mp1[MAXLEN] = {0}, Mp2[MAXLEN] = {0};
char temp[MAXLEN + 3] = {0}, rst[RSTMAX] = {0};
int i = 0, j = 0, t = 0, s = 0;
int len1 = 0, len2 = 0;
int bit = 0;

printf("============= Welcome to Mutip Calculate ============\n");
printf("Please enter two number you want to calculate : \n");
scanf("%s%s", Mp1, Mp2);

len1 = strlen(Mp1);
len2 = strlen(Mp2);
for(j = len2 - 1; j >=0; --j){
for(i = len1 - 1, t = len1; i >= 0; --i, --t){
// let two number not two character to multiply
temp[t] = (Mp1[i] - 0x30) * (Mp2[j] - 0x30);
// 0x30 == 48 == '0'
}

// adjust temp's each bit number which more than 9 to between 0 to 9
for(t = len1; t >0; --t){
if(temp[t] > 9){
temp[t-1] += temp[t]/10;
temp[t] %= 10;
}
}

// sum the new result to the original result;
for(s = len1 + len2 - bit, t = len1; t >= 0; --s, --t){
rst[s] += temp[t];
}

// ajust the new result which more than 9
for(s = len1 + len2; s > 0; --s){
if(rst[s] > 9){
rst[s-1] += rst[s]/10;
rst[s] %= 10;
}
}

// bzero the temp array
for(t = len1; t >= 0; --t){
temp[t] = 0;
}
bit++;
}

// in order to narmal output the result as a string not a interge
rst[len1 + len2 + 1] = '\0';

// switch rst's each bit to character save into the result array.
for(s = 0; s <= len1 + len2; ++s){
rst[s] += 0x30;
}

// delete the first zero before output the result.
for(s = 0; s < len1 + len2; ++s){
if(0x30 == rst[0]){
for(t = 0; t <= len1 + len2 - s; ++t){
rst[t] = rst[t+1];
}
}else{
break;
}
}

// output the result;
printf("%s * %s = %s\n", Mp1, Mp2, rst);
printf("========== Bye Bye ==========\n");
return 0;
}

運行結果如下:
[root@anna-laptop C]# ./Multip
============= Welcome to Mutip Calculate ============
Please enter two number you want to calculate :
123456789
987654321
123456789 * 987654321 = 121932631112635269
========== Bye Bye ==========

Copyright © Linux教程網 All Rights Reserved