我們知道在x86的32位cpu上面,int表示32位,如果核算成整數(shù)的話,大約是40多億。同樣,如果在64位cpu上面,能表示的最大整數(shù)就是64位二進(jìn)制,表示的數(shù)值要大得多。那么在32位如果想表示大整數(shù)怎么辦呢?那只能靠我們自己想辦法了。
首先我們回顧一下我們手算整數(shù)的加減、乘除法是怎么做到的:
(1)記住9*9之間的乘法口訣
(2)記住個(gè)位與個(gè)位之間的加減法
(3)所有乘法用加法和左移位表示,所有的減法用減法和右移位表示
明白上面的道理之后,我們就可以自己手動(dòng)寫一個(gè)大整數(shù)的加法了:
int* big_int_add(int src1[], int length1, int src2[], int length2)
{
int* dest = NULL;
int length;
int index;
int smaller;
int prefix = 0;
if(NULL == src1 || 0 >= length1 || NULL == src2 || 0 >= length2)
return NULL;
length = length1 > length2 ? (length1 + 1) : (length2 + 1);
dest = (int*)malloc(sizeof(int) * length);
assert(NULL != dest);
memset(dest, 0, sizeof(int) * length);
smaller = (length2 < length1) ? length2 : length1;
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];
}
for(index = 0; index < length; index ++){
dest[index] += prefix;
prefix = dest[index] / 10;
dest[index] %= 10;
}
return dest;
}
上面算法最大的特點(diǎn)就是:計(jì)算的時(shí)候沒有考慮10進(jìn)制,等到所有結(jié)果出來之后開始對(duì)每一位進(jìn)行進(jìn)制處理。
討論:
看到上面的算法之后,大家可以考慮一下:
(1)減法應(yīng)該怎么寫呢?
(2)乘法呢?除法呢?