兩個極大整數相乘,結果超出 long long、__int128 甚至任意內置類型範圍。
將數字以字符串/數組形式存儲,每位對應一個十進制數字,模擬豎式乘法:
// 核心邏輯:result[i+j] += a[i] * b[j] + 進位
void multiply(char *a, char *b, char *result) {
int lenA = strlen(a), lenB = strlen(b);
int *temp = calloc(lenA + lenB, sizeof(int));
for (int i = lenA - 1; i >= 0; i--)
for (int j = lenB - 1; j >= 0; j--)
temp[i + j + 1] += (a[i] - '0') * (b[j] - '0');
// 處理進位
for (int k = lenA + lenB - 1; k > 0; k--) {
temp[k - 1] += temp[k] / 10;
temp[k] %= 10;
}
// 轉字符串,跳過前導零
int idx = 0;
for (int k = 0; k < lenA + lenB; k++)
if (idx > 0 || temp[k] > 0) result[idx++] = temp[k] + '0';
result[idx] = '\0';
free(temp);
}
mpz_t)、OpenSSL (BIGNUM)、Boost.Multiprecision (cpp_int)。字符串高精度乘法無理論位數限制,只受內存約束,是解決溢出的通用方法。