P1045 [NOIP2003 普及组] 麦森数
高精度乘法快速幂
//高精度乘法快速幂
#include <bits/stdc++.h>
using namespace std;
int p, length=5e6;
int base[666], ans[666], temp[666];
//将base乘到答案ans中, 实现ans=ans*base;
void mul1()
{
memset(temp, 0, sizeof(temp));
for(int i=1; i<=500; ++i){
for(int j=1; j<=500; ++j){
//避免无效计算
if(i+j-1>500) continue;
temp[i+j-1]+=ans[i]*base[j];
if(temp[i+j-1]>=10){
temp[i+j]+=temp[i+j-1]/10;
temp[i+j-1]%=10;
}
}
}
for(int i=1; i<=500; ++i){
ans[i]=temp[i];
}
}
//base自乘, base=base*base
void mul2()
{
memset(temp, 0, sizeof(temp));
for(int i=1; i<=500; ++i){
for(int j=1; j<=500; ++j){
//避免无效计算
if(i+j-1>500) continue;
temp[i+j-1]+=base[i]*base[j];
if(temp[i+j-1]>=10){
temp[i+j]+=temp[i+j-1]/10;
temp[i+j-1]%=10;
}
}
}
for(int i=1; i<=500; ++i){
base[i]=temp[i];
}
}
int main()
{
scanf("%d", &p);
//第一问:计算位数
//123的位数为3, log10(123)=2.多
//位数为log10(2^p-1) + 1
//等价于log10(2^p) + 1, 因为2^p-1和2^p的位数一样
//等价于p*log10(2) + 1
length= p*log10(2)+1;
printf("%d\n", length);
//第二问:计算后500位的数, 只关心后500位, 所以做高精度乘法时只做500位的乘法
//直接用高精度乘法计算2^p后500位, 时间复杂度为O(500*500*3100000)会超时
//用快速幂思想计算2^p, 结合高精度乘法计算, 时间复杂度为O(500*500*log2(3100000)), 大约为O(5e6)
base[1]=2; //底数初始化为2
ans[1]=1; //答案初始化为1, 否则0乘以任何数一直为0
while(p){
//如果
if(p&1){
//将base乘到答案ans中
mul1();
}
p>>=1;
//base自乘
mul2();
}
//记得减一
ans[1]-=1;
for(int i=500; i>=1; --i){
if(i%50==0 && i!=500){
printf("\n");
}
printf("%d", ans[i]);
}
return 0;
}