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 definition. List of first 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.
Sample Input
3
1
3
13
Output for Sample Input
Case 1: 0.0000000000
Case 2: 2.0000000000
Case 3: 6.0000000000
题解:设数x的期望为dp[x],1到x的素因子个数为m,总素数为n个。
则dp[x]=1+dp[x]*(1-m/n)+dp[x/y]/n; (其中y为1到x的素因子)(其实这个公式就是分两种情况:1:该素数不是x的因子,概率为(1-m/n)期望仍为dp[x]. 2:该素数是x的因子,概率每个为1/n,对应m个并由期望的线性性质得到:dp[x/y]/n,最后的1为一次操作~
化简得dp[x]=(n+dp[x/y])/m;
由于x必由小与x的数递推而来,故可用递归来做。(打好素数表方便计算)
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000010;
int vis[maxn],prime[maxn],tot;
double dp[maxn];//存储答案
void GetPrime()//打好素数表
{
memset(vis,0,sizeof(vis));
for(int i=2;i<=maxn;i++)
{
if(!vis[i])
prime[++tot]=i;
for(int j=1;(j<=tot)&&(i*prime[j]<maxn);j++)
{
vis[i*prime[j]]=1;
if(i%prime[j]==0)
break;
}
}
}
double DFS(int x)
{
if(x==1)//递归终止条件
return 0;
if(vis[x])//优化处理条件
return dp[x];
vis[x]=1;//每算出来一个标记一个
int n=0,m=0;//1到x中总素数个数,素因子个数
double ans=0;//答案
for(int i=1;i<=tot&&prime[i]<=x;i++)
{
n++;
if(x%prime[i]==0)
{
m++;
ans+=DFS(x/prime[i]);//分量
}
}
ans+=n;
ans/=m;
return dp[x]=ans;//记录答案
}
int main()
{
GetPrime();
memset(vis,0,sizeof(vis));//打素数表的时候用到了vis,这时要重新清零
int t,k=1;
cin>>t;
while(t--)
{
int x;
cin>>x;
cout<<"Case "<<k++<<": ";
cout<<fixed<<setprecision(9)<<DFS(x)<<endl;
}
return 0;
}