借陣列實現大整數乘法
阿新 • • 發佈:2018-12-15
思想:
用字串來控制輸入,陣列來儲存,陣列的低位存整數的低位,高位來儲存高位,
和:計算的過程基本上和小學生列豎式做加法相同。
差:跟和差不多
乘:計算的過程基本上和列豎式做乘法相同。為程式設計方便,並不急於處理進位,而將進位問題留待最後統一處理
除:基本的思想是反覆做減法,看看從被除數裡最多能減去多少個除數,商就是多少。一個一個減顯然太慢,如何減得更快一些呢?以7546除以23 為例來看一下:開始商為0。先減去23 的100 倍,就是2300,發現夠減3 次,餘下646。於是商的值就增加300。然後用646 減去230,發現夠減2次,餘下186,於是商的值增加20。最後用186 減去23,夠減8 次,因此最終商就是328。 n的核心是要寫一個大整數的減法函式,然後反覆呼叫該函式進行減法操作。 計算除數的10倍、100 倍的時候,不用做乘法,直接在除數後面補0 即可。
在做資料結構題目的時候遇到了這題,以下參考了的部落格 自己也重新寫了一個大整數乘法的演算法(200位以內),基本思想差不多,其中資料型別的轉換是一個麻煩事,一個巧妙地做法是完成計算後再進行進位運算,感謝!
// 2018/10/14 // 大整數的乘法 用陣列實現 // By Yaaazi? #include <iostream> #include <string> using namespace std; int main() { const int MAX_SIZE = 200; string str1, str2; cin >> str1; cin >> str2; int str1Int[MAX_SIZE], str2Int[MAX_SIZE], str3Int[2 * MAX_SIZE]; for (int k = 0; k < MAX_SIZE; k++) { str1Int[k] = 0; str2Int[k] = 0; } for (int k = 0; k < 2 * MAX_SIZE; k++)str3Int[k] = 0; int lengStr1 = str1.length(); int lengStr2 = str2.length(); for (int i = 0; i < lengStr1; i++) { str1Int[i] = str1[lengStr1 - i - 1] - 48; } string temp1 = ""; for (int i = 0; i < MAX_SIZE ; i++) { temp1 += to_string(str1Int[i]); } cout << temp1 <<endl; for (int i = 0; i < lengStr2; i++) { str2Int[i] = str2[lengStr2 - i - 1] - 48; } string temp2 = ""; for (int i = 0; i < MAX_SIZE; i++) { temp2 += to_string(str2Int[i]); } cout << temp2 << endl; for (int i = 0; i < lengStr2; i++) { for (int j = 0; j < lengStr1; j++) { str3Int[i + j] += str1Int[j] * str2Int[i]; } } cout << lengStr1 << endl; cout << lengStr2 << endl; string temp = ""; for (int i = 0; i < MAX_SIZE * 2; i++) { temp += " " + to_string(str3Int[i]); } cout << temp <<endl; for (int i = 0; i < 2 * MAX_SIZE; i++) { if (str3Int[i] >= 10) { str3Int[i + 1] = (str3Int[i] / 10 + str3Int[i+1]); str3Int[i] %= 10; } } string temp3 = ""; for (int i = 0; i < MAX_SIZE * 2; i++) { temp3 += " " + to_string(str3Int[i]); } cout << temp3 <<endl; int lengStr3 = 0; for (int i = 2 * MAX_SIZE - 1; i >= 0; i--) { if (str3Int[i] != 0) { lengStr3 = i + 1; break; } } cout << lengStr3<<endl; for (int i = lengStr3 - 1; i >= 0; i--) cout << str3Int[i]; return 0; }