1. 程式人生 > >【日常刷題】麥森數 (log函式+快速冪+高精度)

【日常刷題】麥森數 (log函式+快速冪+高精度)

麥森數

第一問:求2p-1的位數。事實上,我們關注2的冪次方的結尾:2,4,8,6,2…不斷迴圈下去,且裡面不包含0。因為也就是求2p的位數。怎麼求?我們可以log10(2^p)+1來表示,若根據對數函式的性質,我們可以變形為:p*log10(2)+1。第一問就這麼解決了。
第二問:設計兩個知識點,快速冪和高精度。(高精度快速冪)這裡不做過多闡述。
CODE

#include<bits/stdc++.h>
using namespace std;
#define MAXN 1200

int p;
int res[MAXN];
int pwNUM[MAXN];

inline
void read(int &be_readNUM) { int s=0,w=1;char c=getchar(); while (c<'0' || c>'9') c=getchar(); while (c<='9' && c>='0') {s=s*10+c-'0'; c=getchar();} be_readNUM=s*w;return; } void Plus() { int temp[MAXN]={}; for (int i=1;i<=500;++i) for (int j=1;j<=
500;++j) temp[i+j-1]+=res[i]*pwNUM[j]; for (int i=1;i<=500;++i) { temp[i+1]+=temp[i]/10; temp[i]%=10; } for (int i=1;i<=500;++i) res[i]=temp[i]; return; } void Power() { int temp[MAXN]={}; for (int i=1;i<=500;++i) for (int j=1;j<=500
;++j) temp[i+j-1]+=pwNUM[i]*pwNUM[j]; for (int i=1;i<=500;++i) { temp[i+1]+=temp[i]/10; temp[i]%=10; } for (int i=1;i<=500;++i) pwNUM[i]=temp[i]; return; } int main() { read(p); printf("%d\n",int(p*log10(2)+1)); res[1]=1;pwNUM[1]=2; while (p>0) { if (p%2==1) Plus(); p/=2; Power(); } res[1]--; for (int i=1;i<=500;++i) if (i%50==0) printf("%d\n",res[501-i]); else printf("%d",res[501-i]); return 0; }