uva 10277 Boastin' Red Socks

红袜子数a 总袜子数b

a*(a - 1)/b*(b-1) = p/q

因为要b最小,所以从2-50000枚举b 二分查找a

注意概率为0和1的情况。

#include <iostream>
#include<stdio.h>
using namespace std;
unsigned long long p,q,d,tmp,tmp1;
unsigned long long low,high,mid,i;

unsigned long long gcd(unsigned long long p,unsigned long long q)
{
    return q == 0?p:gcd(q,p%q);
}

int main()
{
    while(scanf("%llu %llu",&p,&q),p+q)
    {
        if(p==q)
        {
            printf("2 0\n");
            continue;
        }
        if(p==0) {printf("0 2\n");continue;}
        d = gcd(p,q);
        p/=d;
        q/=d;
        int ok = 0;
        for(i = 2; i<=50000; i++)
        {
            low = 2;
            high = i;
            tmp = p*i*i-p*i;
            while(low <= high)
            {
                mid = (low+high)>>1;
                tmp1 = mid*mid*q-mid*q;
                if(tmp1<tmp) low = mid+1;
                else if(tmp1 > tmp) high = mid-1;
                else { printf("%llu %llu\n",mid,i-mid);ok = 1;break;}
            }
            if(ok) break;
        }
        if(!ok) printf("impossible\n");
    }
    return 0;
}


你可能感兴趣的:(uva 10277 Boastin' Red Socks)