OpenJudge百炼-2706-麦森数-C语言-高精度计算

来源:互联网 发布:电影社交网络中的博客 编辑:程序博客网 时间:2024/05/29 00:31

描述:
形如2p-1的素数称为麦森数,这时P一定也是个素数。但反过来不一定,即如果P是个素数。2p-1不一定也是素数。到1998年底,人们已找到了37个麦森数。最大的一个是P=3021377,它有909526位。麦森数有许多重要应用,它与完全数密切相关。
任务:从文件中输入P (1000<P<3100000) ,计算2p-1的位数和最后500位数字(用十进制高精度数表示)
输入:
文件中只包含一个整数P(1000<P<3100000)
输出:
第1行:十进制高精度数2p-1的位数。
第2-11行:十进制高精度数2p-1的最后500位数字。(每行输出50位,共输出10行,不足500位时高位补0)
不必验证2p-1与P是否为素数。
样例输入:
1279
样例输出:
386
00000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
00000000000000104079321946643990819252403273640855
38615262247266704805319112350403608059673360298012
23944173232418484242161395428100779138356624832346
49081399066056773207629241295093892203457731833496
61583550472959420547689811211693677147548478866962
50138443826029173234888531116082853841658502825560
46662248318909188018470682222031405210266984354887
32958028878050869736186900714720710555703168729087

/**************************************************文件名:百炼-2706**Copyright (c) 2015-2025 OrdinaryCrazy**创建人:OrdinaryCrazy**日期:20170814**描述:百炼2706参考答案**版本:1.0*************************************************/#include <stdio.h>#include <math.h>#include <string.h>/***********************************************假设2^p有n位,即2^p = 10^n + an = log10(2^p-a)=log10(2^p)=p*log(2)输出的位数由math.h中的log10函数计算p = a(0)*2^0 + a(1)*2^1 +....+ 2^n (其中a(n)是p的各二进制位)2^p = 2^(a(0)*2^0) * ... * 2^(2^n)为了避免超时,大整数以10000进制存储************************************************//***********************************************大整数a,b相乘,末500位存放在a中************************************************/void mul(int * a,int *b){    int i,j,res[125];    memset(res,0,sizeof(res));    for(i = 0;i < 125;i++)        for(j = 0;j < 125-i;j++)        {            res[i+j] += a[i] * b[j];            res[i+j+1] += res[i+j]/10000;            res[i+j] %= 10000;        }    memcpy(a,res,sizeof(res));}int p,result[125],assit[125]/**用来存放2^(2^n)**/;int main(){    int i;    scanf("%d",&p);    printf("%d\n",(int)(p*log10(2.0))+1);    result[0] = 1;    assit[0] = 2;    while(p)    {        if(p & 1)            mul(result,assit);        p >>= 1;        mul(assit,assit);    }    result[0]--;    for(i = 124;i >= 0;i--)        if(i % 25 == 12)            printf("%02d\n%02d",result[i]/100,result[i]%100);        else        {            printf("%04d",result[i]);            if(i % 25 == 0)printf("\n");        }    return 0;}


阅读全文
0 0
原创粉丝点击