UVA 10214(p339)----Trees in a Wood

#include<iostream>
#include<cstdio>
using namespace std;
typedef unsigned long long ULL;
const int maxn=2010;
int phi[maxn+50];
int mindiv[maxn+50];
void prepare()
{
    for(int i=1; i<maxn; i++)
        mindiv[i]=i;
    for(int i=2; i*i<maxn; i++)
        if(mindiv[i]==i)
        {
            for(int j=i*i; j<maxn; j+=i)
                mindiv[j]=i;
        }
    phi[1]=1;
    for(int i=2; i<maxn; i++)
    {
        phi[i]=phi[i/mindiv[i]];
        if((i/mindiv[i])%mindiv[i]==0)
            phi[i]*=mindiv[i];
        else
            phi[i]*=mindiv[i]-1;
    }
}
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int main()
{
    int a,b;
    prepare();
    while(scanf("%d%d",&a,&b)==2&&(a+b))
    {
        ULL all=(ULL)4*a*b+2*(a+b);
        ULL ans=0;
        for(int i=1;i<=a;i++)
        {
            ans+=(b/i)*phi[i];
            int tmp=b%i;
            for(int j=1;j<=tmp;j++)
                if(gcd(i,j)==1) ans++;
        }
        ans*=4;ans+=4;
        printf("%.7lf\n",(double)ans/(double)all);
    }
    return 0;
}

你可能感兴趣的:(UVA 10214(p339)----Trees in a Wood)