杰哥私房题──麦森数

问题描述
形如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

 

#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
const int LEN = 125;

void multiply(int* a, int* b){
	int c[LEN];
	memset(c, 0, sizeof(c));
	int nCarry, total = 0;
	for(int i = 0; i < LEN; i++){
		nCarry = 0;
		for(int j = 0; j < LEN - i; j ++){//因为只要500位,所以算到125-i-1就够了
			total = c[i + j] + a[j] * b[i] + nCarry;
			c[i + j] = total % 10000;
			nCarry = total / 10000;
		}
	}
	memcpy(a, c, sizeof(c));
}

int main(){
	int p;
	cin >> p;
	cout << (int)(p * log10(2)) + 1 << endl;
	int anPow[LEN];
	int result[LEN];	
	anPow[0] = 2;
	result[0] = 1;
	for(int i = 1; i < LEN; i++){
		anPow[i] = 0;
		result[i] = 0;
	}
	while(p > 0){
		if(p & 1)
			multiply(result, anPow);
		p>>= 1;
		multiply(anPow, anPow);
	}
	result[0] --;
	for(int i = LEN - 1; i >= 0; i--){
		if(i % 25 == 12)
			printf("%02d\n%02d", result[i] / 100, result[i] % 100);
		else{
			printf("%04d", result[i]);
			if(i % 25 == 0)
				cout << endl;
		}
	}
	return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值