位数计算 由于梅森数可能十分巨大,因此计算梅森数的精确位数,需要运用换底公式:log10(2^p)=p*ln(2)/ln(10),然后加1再取整即可。(因为10^n有n+1位,所以要加1)。
计算梅森数的位数的C++源代码如下:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main(){
int p;
cout<<"Please input a prime number p:";
cin>>p;
cout<<"M"<<p<<" is a "<<int(p*log10(2)+1)<<"-digit number.\n";
return 0;
}
问题1. 麦森数 【问题描述】形如2P-1的素数称为麦森数,这时P一定也是个素数。但反过来不一定,即如果P是个素数,2P-1不一定也是素数。到1998年底,人们已找到了37个麦森数。最大的一个是P=3021377,它有909526位。麦森数有许多重要应用,它与完全数密切相关。 任务:从文件中输入P(1000<P<3100000),计算2P-1的位数和最后500位数字(用十进制高精度数表示) 【输入格式】 文件中只包含一个整数P(1000<P<3100000) 【输出格式】 第一行:十进制高精度数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
算法:2的幂可以转化成左移运算,为了提高运算速度,可每次左移10位,即每次乘210。对于个位单独考虑,每次左移一位。源程序如下:
#include <stdio.h>
#include <math.h>
#define MAX 100000
main()
{
int p;
int i, j;
scanf("%d", &p);
printf("%d\n", (int)(p * log10(2.0)) + 1);
long store[110] = {0};
store[0] = 1;
int left = p % 10;
p /= 10;
for(i = 1; i <= p; i++)
{
for(j = 0; j <= 100; j++)
store[j] <<= 10;
for(j = 0; j <= 100; j++)
{
if(store[j] >= MAX)
{
store[j + 1] += store[j] / MAX;
store[j] %= MAX;
}
}
}
for(i = 1; i <= left; i++)
{
for(j = 0; j <= 100; j++)
store[j] <<= 1;
for(j = 0; j <= 100; j++)
{
if(store[j] >= MAX)
{
store[j + 1] += store[j] / MAX;
store[j] %= MAX;
}
}
}
store[0] -= 1;
for(i = 1; i < 100; i++)
{
if(store[i - 1] < 0)
{
store[i] -= 1;
store[i - 1] += MAX;
}
else
break;
}
for(i = 99; i >= 0; i--)
{
printf("%05d", store[i]);
if((100 - i) % 10 == 0)
printf("\n");
}
}