百练#2706麦森数

描述
形如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<cstring>
#include<cmath>
#define LEN 125
using namespace std;
int result[LEN];
int tpow[LEN];
void mul(int *a,int *b){
	int temp[LEN];
	int jin,t;
	memset(temp,0,sizeof(int) * LEN);
	for(int i = 0;i < LEN; ++i){
		jin = 0;
		for(int j = 0;j < LEN - i; ++j){
			t = temp[i + j] + a[i] * b[j] + jin;
			temp[i + j] = t % 10000;
			jin = t / 10000; 
		}
	}
	memcpy(a,temp,sizeof(int) * LEN);
}
int main(){
	int p;
	int i,j;
	scanf("%d",&p);
	printf("%d\n",(int)(p * log10(2)) + 1);
	memset(result,0,sizeof(int) * LEN);
	result[0] = 1;
	memset(tpow,0,sizeof(int) * LEN);
	tpow[0] = 2;
	while(p > 0){
		if(p & 1){
			mul(result,tpow);
		}
		mul(tpow,tpow);
		p >>= 1;
	}
	result[0]--;
	j = 0;
	for(i = LEN - 1;i >= 0; --i){
		if((j + 2) % 50 == 0)
			printf("%02d\n%02d",result[i] / 100,result[i] % 100);
		else if((j + 4) % 50 == 0)
			printf("%04d\n",result[i]);
		else
			printf("%04d",result[i]);
		j += 4;
	}
	printf("\n");
	return 0;
}
 

错误:只会TLE的方法
别人的代码:
1.万进制数,缩减时间;
2.位运算缩减时间。
就是一个求指数的模板。

发布了53 篇原创文章 · 获赞 0 · 访问量 734

猜你喜欢

转载自blog.csdn.net/weixin_38894974/article/details/104231970