题目
算法
(高精度,快速幂,数学) O ( 50 0 2 l o g P ) O(500^2logP) O(5002logP)
首先考虑如何求位数。
我们发现在 1 0 k ∼ 1 0 k + 1 − 1 10^k∼10^{k+1}−1 10k∼10k+1−1, ( k ≥ 0 ) (k≥0) (k≥0)之间的数均有 k + 1 k+1 k+1 位。因此对于任意正整数 x x x,它的位数是 ⌊ l o g 10 x ⌋ + 1 ⌊log10x⌋+1 ⌊log10x⌋+1。
而由于2的整次幂的末位数字不为0,因此 2 P − 1 2^P−1 2P−1的位数和 2 P 2^P 2P 的位数相同,所以 2 P − 1 2^P−1 2P−1 的位数是 ⌊ l o g 10 2 P ⌋ + 1 = ⌊ P l o g 10 2 ⌋ + 1 ⌊log_{10}2^P⌋+1=⌊Plog_{10}2⌋+1 ⌊log102P⌋+1=⌊Plog102⌋+1。
cmath库中有函数 log10(),直接使用即可。
然后考虑如何求最后500位数。
- 直接乘 P P P 次,时间复杂度是 500 P = 1.5 × 1 0 9 500P=1.5×10^9 500P=1.5×109
- 用快速幂,时间复杂度是 50 0 2 l o g P = 5 × 1 0 6 500^2logP=5×10^6 5002logP=5×106
因此我们选择第二种方法。
时间复杂度
算法瓶颈在于求用快速幂 + 高精度,计算量是 O ( 50 0 2 l o g P ) O(500^2logP) O(5002logP)。
C++代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 500;
int p;
int a[N], tmp[N], res[N];
void mul(int c[], int a[], int b[])
{
memset(tmp, 0, sizeof tmp);
for(int i = 0; i < N; i++)
for(int j = 0; i + j < N; j++)
tmp[i + j] += a[i] * b[j];
for(int i = 0, t = 0; i < N; i++)
{
t += tmp[i];
c[i] = t % 10;
t /= 10;
}
}
void qui(int k)
{
res[0] = 1;
a[0] = 2;
while(k)
{
if(k & 1)
mul(res, res, a);
mul(a, a, a);
k >>= 1;
}
res[0]--;
}
int main()
{
cin >> p;
cout << int(p * log10(2)) + 1 << endl;
qui(p);
for(int i = 0, k = N - 1; i < 10; i++)
{
for(int j = 0; j < 50; j++, k--)
cout << res[k];
cout << endl;
}
return 0;
}