题目描述
形如 2 P − 1 2^{P}-1 2P−1 的素数称为麦森数,这时 P P P 一定也是个素数。但反过来不一定,即如果 P P P 是个素数, 2 P − 1 2^{P}-1 2P−1 不一定也是素数。到 1998 年底,人们已找到了 37 个麦森数。最大的一个是 P = 3021377 P=3021377 P=3021377,它有 909526 位。麦森数有许多重要应用,它与完全数密切相关。
任务:输入 P ( 1000 < P < 3100000 ) P(1000<P<3100000) P(1000<P<3100000),计算 2 P − 1 2^{P}-1 2P−1 的位数和最后 500 500 500 位数字(用十进制高精度数表示)
输入格式
文件中只包含一个整数 P ( 1000 < P < 3100000 ) P(1000<P<3100000) P(1000<P<3100000)
输出格式
第一行:十进制高精度数 2 P − 1 2^{P}-1 2P−1 的位数。
第 2 ∼ 11 2\sim 11 2∼11 行:十进制高精度数 2 P − 1 2^{P}-1 2P−1 的最后 500 500 500 位数字。(每行输出 50 50 50 位,共输出 10 10 10 行,不足 500 500 500 位时高位补 0 0 0)
不必验证 2 P − 1 2^{P}-1 2P−1 与 P P P 是否为素数。
样例 #1
样例输入 #1
1279
样例输出 #1
386
00000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
00000000000000104079321946643990819252403273640855
38615262247266704805319112350403608059673360298012
23944173232418484242161395428100779138356624832346
49081399066056773207629241295093892203457731833496
61583550472959420547689811211693677147548478866962
50138443826029173234888531116082853841658502825560
46662248318909188018470682222031405210266984354887
32958028878050869736186900714720710555703168729087
提示
【题目来源】
NOIP 2003 普及组第四题
分析
- 如何求2p-1的位数,首先,2p-1不会影响2p的位数,那么问题就是如何求2p的位数,先观察一下10p的位数为p+1,我们能不能把2p转换为10p的格式,进一步简化问题,根据高中所学知识,2显然等于10log102,那么就等于求(10log102)p的位数,位数为p*log102+1。
- 问题只需要求后500位数字,可以限制高精度乘法只求后500位,这样能节约时间,避免P太大造成tle。
代码
#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
int a[1010], res[1010];
void mul_1() {//高精度
int temp[1010];
memset(temp, 0, sizeof temp);
for (int i = 0; i < 500; i++)
for (int j = 0; j < 500; j++)
temp[i + j] += res[i] * a[j];
int t = 0;
for (int i = 0; i < 500; i++) {
temp[i] += t;
res[i] = temp[i] % 10;
t = temp[i] / 10;
}
}
void mul_2() {
int temp[1010];
memset(temp, 0, sizeof temp);
for (int i = 0; i < 500; i++)
for (int j = 0; j < 500; j++)
temp[i + j] += a[i] * a[j];
int t = 0;
for (int i = 0; i < 500; i++) {
temp[i] += t;
a[i] = temp[i] % 10;
t = temp[i] / 10;
}
}
void quickmi(ll p) {//快速幂
res[0] = 1;
a[0] = 2;
while (p) {
if (p & 1)mul_1();
mul_2();
p >>= 1;
}
}
int main() {
ll p;
cin >> p;
quickmi(p);
cout << (int)(p * log10(2) + 1);
res[0]--;
for (int i = 499; i >=0; i--) {
if ((i+1) % 50 == 0)puts("");
printf("%d", res[i]);
}
}