大数乘法(C语言实现)
實(shí)現(xiàn)過(guò)程分析:
我們回憶一下,在我們小時(shí)候剛接觸多位數(shù)的乘法,我們的數(shù)學(xué)老師會(huì)教給我們一個(gè)方法,那就是“乘法的豎式計(jì)算”。在這里我們就采用該思想解決大數(shù)乘法的問(wèn)題。
以下是我們經(jīng)常進(jìn)行乘法的豎式運(yùn)算:
根據(jù)以上的豎式運(yùn)算,我們實(shí)現(xiàn)過(guò)程總結(jié)如下:
1、先使用兩個(gè)字符數(shù)組保存兩個(gè)大數(shù)據(jù);
2、用第一個(gè)數(shù)據(jù)的個(gè)位與第二個(gè)數(shù)據(jù)的所有位相乘,并將每一位的運(yùn)算結(jié)果保存在暫存字符數(shù)組temp中,并進(jìn)行進(jìn)位調(diào)整,即如果該位的數(shù)值大于9,就將該數(shù)值的十位加到前一位,并將該位的個(gè)位保存在原位。
3、將temp與結(jié)果數(shù)組rst中的數(shù)值逆序相加,也就是從兩個(gè)數(shù)組的倒數(shù)第一位開(kāi)始相加。
4、以相同的方法,計(jì)算出第一個(gè)數(shù)據(jù)的十位與第二個(gè)數(shù)據(jù)相乘的結(jié)果,并保存至temp中。
5、將temp與rst倒數(shù)第二位的結(jié)果開(kāi)始逆序相加。
6、第一個(gè)數(shù)據(jù)有幾位就將以上過(guò)程進(jìn)行幾次。
注:對(duì)于確定每次與rst的倒數(shù)第幾位相加時(shí),可以采用一個(gè)bit變量存下正在進(jìn)行第一個(gè)數(shù)據(jù)的第幾位數(shù)據(jù)的運(yùn)算,在最終相加時(shí),在rst數(shù)組的末尾減去bit就是,應(yīng)該與temp最后一位相加的位數(shù)。
C語(yǔ)言實(shí)現(xiàn)過(guò)程:
OK! 我們可以帶著對(duì)這個(gè)乘法豎式的重新理解來(lái)解決我們的大數(shù)乘法問(wèn)題,以下是C語(yǔ)言實(shí)現(xiàn)的代碼:
#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 multiplytemp[t] = (Mp1[i] - 0x30) * (Mp2[j] - 0x30); // 0x30 == 48 == '0'} // adjust temp's each bit number which more than 9 to between 0 to 9for(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 arrayfor(t = len1; t >= 0; --t){temp[t] = 0;}bit++;}// in order to narmal output the result as a string not a intergerst[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; }運(yùn)行結(jié)果如下:
[root@anna-laptop C]# ./Multip ============= Welcome to Mutip Calculate ============ Please enter two number you want to calculate : 123456789 987654321 123456789 * 987654321 = 121932631112635269 ========== Bye Bye ==========總結(jié)
以上是生活随笔為你收集整理的大数乘法(C语言实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux ubuntu安装教程6,1.
- 下一篇: SylixOS 共用中断号机制