麦森数【洛谷P1045】

it2022-05-05  110

题目描述

形如2P−12{P}-12P−1的素数称为麦森数,这时PPP一定也是个素数。但反过来不一定,即如果PPP是个素数,2P−12{P}-12P−1不一定也是素数。到1998年底,人们已找到了37个麦森数。最大的一个是P=3021377P=3021377P=3021377,它有909526位。麦森数有许多重要应用,它与完全数密切相关。

任务:从文件中输入PPP(1000<P<31000001000<P<31000001000<P<3100000),计算2P−12^{P}-12P−1的位数和最后500位数字(用十进制高精度数表示) 输入输出格式 输入格式:

文件中只包含一个整数PPP(1000<P<31000001000<P<31000001000<P<3100000)

输出格式:

第一行:十进制高精度数2P−12^{P}-12P−1的位数。

第2-11行:十进制高精度数2P−12^{P}-12P−1的最后500位数字。(每行输出50位,共输出10行,不足500位时高位补0)

不必验证2P−12^{P}-12P−1与PPP是否为素数。

输入输出样例 输入样例#1: 复制

1279

输出样例#1: 复制

386 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000104079321946643990819252403273640855 38615262247266704805319112350403608059673360298012 23944173232418484242161395428100779138356624832346 49081399066056773207629241295093892203457731833496 61583550472959420547689811211693677147548478866962 50138443826029173234888531116082853841658502825560 46662248318909188018470682222031405210266984354887 32958028878050869736186900714720710555703168729087

思路

高精度乘法+快速幂 code

#include <stdio.h> #include <iostream> #include <string.h> #include <math.h> #include <cmath> using namespace std; int p,len,n; void mul(int *a,int *b) { int i,j; int c[600]; memset(c,0,sizeof(c)); for (i=1;i<=500;i++) for (j=1;j<=500;j++) if (i+j-1<=500) { c[i+j-1]+=a[i]*b[j]; c[i+j]+=c[i+j-1]/10; c[i+j-1]%=10; } memcpy(a+1,c+1,500*sizeof(int)); } int main() { int ans[600]; int a[600]; int i,j,b; memset(a, 0, sizeof(a)); memset(ans, 0, sizeof(ans)); scanf("%d",&p); ans[1]=1; a[1]=2; int t=log(2.0)/log(10.0)*p+1; printf("%d\n",t); b=p; while (b>0) { if (b%2==1) mul(ans,a); b/=2; mul(a,a); } ans[1]--; for (i=500;i>=1;i--) { if (i!=500&&i%50==0) printf("\n"); printf("%d",ans[i]); } return 0; }

最新回复(0)