32 位 CPU 下 int 僅能表示約 40 億,64 位雖擴大但仍有上限。當需處理超大整數時,必須模擬人工豎式運算邏輯。本文解析大整數加法的核心思想:先逐位相加不進位,再統一處理進位,並提供完整 C 語言實作。
int* big_int_add(int src1[], int length1, int src2[], int length2) {
if (NULL == src1 || 0 >= length1 || NULL == src2 || 0 >= length2) return NULL;
int length = (length1 > length2 ? length1 : length2) + 1; // 預留進位位
int* dest = (int*)malloc(sizeof(int) * length);
assert(NULL != dest);
memset(dest, 0, sizeof(int) * length);
int smaller = (length1 < length2) ? length1 : length2;
int index;
// 階段一:對應位相加,不處理進位
for (index = 0; index < smaller; index++)
dest[index] = src1[index] + src2[index];
// 階段二:處理較長數組剩餘位
if (length1 > length2) {
for (; index < length1; index++) dest[index] = src1[index];
} else {
for (; index < length2; index++) dest[index] = src2[index];
}
// 階段三:統一處理進位(核心創新點)
int prefix = 0;
for (index = 0; index < length; index++) {
dest[index] += prefix;
prefix = dest[index] / 10;
dest[index] %= 10;
}
return dest;
}
max(len1, len2) + 1,確保最高位進位有空間理解加法後,可嘗試實作:
核心皆為「將大數拆解為單位位陣列,模擬人工豎式邏輯」。
大數運算不依賴硬體指令,純軟體模擬即可突破位寬限制。此思想廣泛應用於密碼學(RSA 大數模運算)、高精度科學計算等領域。掌握「分階段處理」與「陣列模擬位運算」是關鍵。