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;
}