Dilu have learned a new thing about integers, which is - any positive
integer greater than 1 can be divided by at least one prime number
less than or equal to that number. So, he is now playing with this
property. He selects a number N . And he calls this D . In each turn
he randomly chooses a prime number less than or equal to D . If D is
divisible by the prime number then he divides D by the prime number to
obtain new D . Otherwise he keeps the old D . He repeats this
procedure until D becomes 1. What is the expected number of moves
required for N to become 1. [We say that an integer is said to be
prime if its divisible by exactly two different integers. So, 1 is not
a prime, by de nition. List of rst few primes are 2, 3, 5, 7, 11,
…] Input Input will start with an integer T ( T 1000), which
indicates the number of test cases. Each of the next T lines will
contain one integer N (1 N 1000000). Output For each test case
output a single line giving the case number followed by the expected
number of turn required. Errors up to 1e-6 will be accepted.
设
dp(i)
表示从
i
开始的期望步数,有
化简得
记忆化搜索。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define LL long long
const int maxx=1000000;
int prm[1000010],tot,have[1000010];
double dp[1000010];
double dfs(int x)
{
if (x==1) return 0;
if (dp[x]) return dp[x];
int m=0,n=0,i;
for (i=1;i<=tot&&prm[i]<=x;i++)
{
n++;
if (x%prm[i]==0) dp[x]+=dfs(x/prm[i]),m++;
}
return dp[x]=(dp[x]+n)/m;
}
int main()
{
int T,K,i,j,x;
for (i=2;i<=maxx;i++)
{
if (!have[i]) prm[++tot]=i;
for (j=1;j<=tot&&(LL)prm[j]*i<=maxx;j++)
{
have[prm[j]*i]=1;
if (i%prm[j]==0) break;
}
}
scanf("%d",&T);
for (K=1;K<=T;K++)
{
scanf("%d",&x);
printf("Case %d: %.10f\n",K,dfs(x));
}
}