求大数(用数组存放)

来源:互联网 发布:js加密压缩后怎么调用 编辑:程序博客网 时间:2024/05/18 21:08

#include<stdio.h>
#include<stdlib.h>

//****************************
//大数运算
//1+2+4+8+.......+2^100 =
//思路:用足够大的数组存放结果
//求2^101-1
//****************************

#define N 1000        //设置足够大的数组存放位数

int res[N];

int bigNumber(int num)
{
        int flag=0;        //设置进位
        int        total=1;        //返回总位数
        int count;
        int i,temp;
        res[0] = 1;
        for(i=0;i<num;i++)
        {
                for(count=0;count<total;count++)
                {
                        temp = (res[count]<<1)+ flag;        //每个位数与2相乘
                        res[count] = temp%10;
                        flag = temp/10;
                }
                while(flag)        //有进位
                {
                        res[total] = flag%10;        //flag有可能大于10?
                        flag = flag/10;
                        total++;        //总位数+1
                }//for count
        }//for i
        res[0] -= 1;
        return total; //返回总位数
}
int main()
{
        int m_total;
        int i;
        int m_num = 101;
        printf("2^101-1 = ");
        m_total = bigNumber(101);
        for(i=m_total-1;i>=0;i--)
                printf("%d",res);
        printf("/n");
      system("pause");
        return 0;
        }

原创粉丝点击