R - Race to 1 (期望)

22 篇文章 0 订阅
4 篇文章 0 订阅

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)+\sumdp[x/y]/n;     (其中y为1到x的素因子)(其实这个公式就是分两种情况:1:该素数不是x的因子,概率为(1-m/n)期望仍为dp[x]. 2:该素数是x的因子,概率每个为1/n,对应m个并由期望的线性性质得到:\sumdp[x/y]/n,最后的1为一次操作~

化简得dp[x]=(n+\sumdp[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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值