10277 - Boastin' Red Socks
Time limit: 3.000 seconds
You have a drawer that is full of two kinds of socks: red and black. You know that there are at least 2 socks, and not more than 50000. However, you do not know how many there actually are, nor do you know how many are red, or how many are black. (Your mother does the laundry!)
You have noticed, though, that when you reach into the drawer each morning and choose two socks to wear (in pitch darkness, so you cannot distinguish red from black), the probability that you pick two red socks is exactlyp/q, where 0 < q and 0 <= p <= q.
From this, can you determine how many socks of each colour are in your drawer? There may be multiple solutions - if so, pick the solution with the fewest total number of socks, but still allowing you to wear a couple of same color socks.
Input
Input consists of multiple problems, each on a separate line. Each problem consists of the integers p and q separated by a single space. Note that p and q will both fit into an unsigned long integer.Input is terminated by a line consisting of two zeroes.
Output
For each problem, output a single line consisting of the number of red socks and the number of black socks in your drawer, separated by one space. If there is no solution to the problem, print "impossible".Sample Input
1 2 6 8 12 2499550020 56 789 0 0
Sample Output
3 1 7 1 4 49992 impossible
思路:设红袜子有x只,黑袜子有y只,则有
C(x,2)/C(x+y,2)=x(x-1)/((x+y)(x+y-1))=p/q
所以枚举分母i,看是否满足q|(i*(i-1)),然后据此看对应的p能否拆分成j*(j-1)的形式
PS:此题可化为一个二元二次丢番图方程
[(q-p)(2x-1)-p(2y)]^2 - pq(2y)^2 = (q-p)^2,当q-p!=1时其不一定有解,更具体的分析?(坑)
完整代码:(跑0ms是因为提交时恰逢UVa服务器故障(俗称大姨妈))
/*0.000s*/
#include <cstdio>
#include <cmath>
typedef unsigned int ll;
const ll maxn = 50000;
ll gcd(ll a , ll b)
{
return b ? gcd(b, a % b) : a;
}
int main()
{
ll p, q, g, i, pp;
double j;
while (scanf("%u%u", &p, &q), q)
{
if (p == 0) /// 概率为0
{
puts("0 2"); /// at least 2 socks
continue;
}
g = gcd(p, q);
p /= g, q /= g;
for (i = 2; i <= maxn; ++i) /// not more than 50000
if (i * (i - 1) % q == 0) /// 符合条件的分母
{
pp = i * (i - 1) / q * p;
j = sqrt(0.25 + pp) + 0.5;
if (round(j) == j) /// 分子也符合条件
{
printf("%u %u\n", (ll)j, i - (ll)j);
break;
}
}
if (i > maxn) puts("impossible");
}
return 0;
}