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 exactly p/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.
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
Source: Waterloo Local Contest Jun. 19, 1999
设红色袜子数为r,总共为t,黑色袜子数即为t-r。由题意:
r(r-1) / t(t-1) = p/q。
#include <iostream> #include <math.h> using namespace std; long long gcd(long long a,long long b){ return b==0 ? a : gcd(b,a%b); } int main(){ long long p,q,g,r,t,h,d; while(cin>>p>>q,p,q){ if(p == 0){ cout<<0<<" "<<2<<endl; continue; } g = gcd(p,q);cout<<g<<endl; p /= g; q /= g;//让pq互质 bool f = false; for(t=2;t<=50000;t++){//枚举总袜子数t if(t*(t-1)%q==0){//可行的 t值 h = t*(t-1)/q*p; d = sqrt(4*h+1);//求根公式 if(d*d!=4*h+1) continue; if((d+1)%2==0){ r=(d+1)/2; cout<<r<<" "<<t-r<<endl; f = true; break; } } } if(!f) cout<<"impossible"<<endl; } return 0; }
奇怪的地方是,用unsigned long 得到WA,可能是涉及相乘位数不够吧。
本文探讨了一种基于袜子颜色概率确定袜子数量的问题。通过分析红色和黑色袜子从抽屉中被随机取出的概率,利用数学公式和编程实现,解决如何确定抽屉中两种颜色袜子的具体数量。文章提供了一个C++程序示例,用于计算不同概率下可能的袜子组合。
99

被折叠的 条评论
为什么被折叠?



