p1045麦森数(高精快速幂)

题目描述

形如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是否为素数。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;

typedef long long ll;
int a[600];
int ans[1200];
int cur[1200];

void solve1()
{
	mem(cur, 0);
	for(int i = 1; i <= 500; i++)
		for(int j = 1; j <= 500; j++)
		{
			cur[i + j - 1] += ans[i] * a[j];
			cur[i + j] += cur[i + j - 1] / 10;
			cur[i + j - 1] %= 10;
		}
//	cout << cur[1] << cur[2] << endl;
	memcpy(ans, cur, sizeof(ans));
}

void solve2()
{
	mem(cur, 0);
	for(int i = 1; i <= 500; i++)
		for(int j = 1; j <= 500; j++)
		{
			cur[i + j - 1] += a[i] * a[j];
			cur[i + j] += cur[i + j - 1] / 10;
			cur[i + j - 1] %= 10;
		}
//	cout << a[2] << a[1] << ' ';
	memcpy(a, cur, sizeof(a));
}


int main()
{
	int p;
	cin >> p;
	cout << int(log10(2) * p) + 1 << endl;
	ans[1] = 1;
	a[1] = 2;
	while(p != 0)
	{
//		cout << ans[1] << ans[2] << endl;
		if(p & 1)
		{
			solve1();
		}
		p >>= 1;
		solve2();
//		cout << a[3] << a[2] << a[1] << endl;
	}
	ans[1] -= 1;
	for(int i = 500; i > 0; i--)
	{
		if(i != 500 && i % 50 == 0)
			cout << endl;
		cout << ans[i];
	}
	return 0;
}
发布了73 篇原创文章 · 获赞 15 · 访问量 8099

猜你喜欢

转载自blog.csdn.net/ln2037/article/details/102792638