2706:麥森數
-
總時間限制:
- 1000ms
- 內存限制:
- 65536kB
-
描述
- 形如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
思路:位數計算,對於10來說取對數,log10000=4 ,共5位。一個十進制數有多少位就是10的多少次方+1,所以對2^p這個十進制數取對數,然後結果加一,就是位數。 只需要計算後500位,那麼用長度100的數組來存,每次存5位。
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define mod 100000
using namespace std;
int ans[110];
int main()
{
int p;
while(~scanf("%d",&p))
{
printf("%d\n",(int)(p*log10(2*1.0))+1);
memset(ans,0,sizeof ans);
ans[0]=1;
int yu=p%10; //餘下不足10次單獨計算
p/=10; //每次計算10位,共計算p/10次
for(int i=1; i<=p; i++)
{
for(int j=0; j<=100; j++) //ans每個單位存一個5位數,計算100個單位,共5*100=500位
ans[j]<<=10;
for(int j=0; j<=100; j++)
{
if(ans[j]>=mod)
{
ans[j+1]+=ans[j]/mod; //當前ans[j]超過五位數就向前進位
ans[j]%=mod;
}
}
}
for(int i=1; i<=yu; i++)
{
for(int j=0; j<=100; j++) //每次乘以2
ans[j]<<=1;
for(int j=0; j<=100; j++)
{
if(ans[j]>=mod)
{
ans[j+1]+=ans[j]/mod; //當前ans[j]超過五位數就向前進位
ans[j]%=mod;
}
}
}
ans[0]--; //2^p總是以2,4,6,8結尾
for(int i=99; i>=0; i--)
{
printf("%05d",ans[i]);
if(i%10==0)
puts("");
}
// puts("");
}
return 0;
}