频道栏目
首页 > 资讯 > C语言 > 正文

一步一步写算法(之大数计算)

11-10-23        来源:[db:作者]  
收藏   我要投稿

 

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

 

 

 

 

    我们知道在x86的32位cpu上面,int表示32位,如果核算成整数的话,大约是40多亿。同样,如果在64位cpu上面,能表示的最大整数就是64位二进制,表示的数值要大得多。那么在32位如果想表示大整数怎么办呢?那只能靠我们自己想办法了。

 

    首先我们回顾一下我们手算整数的加减、乘除法是怎么做到的:

 

    (1)记住9*9之间的乘法口诀

 

    (2)记住个位与个位之间的加减法

 

    (3)所有乘法用加法和左移位表示,所有的减法用减法和右移位表示

 

    明白上面的道理之后,我们就可以自己手动写一个大整数的加法了:

 

 

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; 

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;

}    上面算法最大的特点就是:计算的时候没有考虑10进制,等到所有结果出来之后开始对每一位进行进制处理。

 

 

 

 

讨论:

 

    看到上面的算法之后,大家可以考虑一下:

 

    (1)减法应该怎么写呢?

 

    (2)乘法呢?除法呢?

相关TAG标签
上一篇:正则模式修饰符
下一篇:一步一步写算法(之链表逆转)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站