UVa10375
Choose and divide
The binomial coefficient C(m; n) is defined as
C(m; n) =
m!
(m n)! n!
Given four natural numbers p, q, r, and s, compute the the result of dividing C(p; q) by C(r; s).
Input
Input consists of a sequence of lines. Each line contains four non-negative integer numbers giving values
for p, q, r, and s, respectively, separated by a single space. All the numbers will be smaller than 10,000
with p q and r s.
Output
For each line of input, print a single line containing a real number with 5 digits of precision in the fraction,
giving the number as described above. You may assume the result is not greater than 100,000,000.
Sample Input
10 5 14 9
93 45 84 59
145 95 143 92
995 487 996 488
2000 1000 1999 999
9998 4999 9996 4998
Sample Output
0.12587
505606.46055
1.28223
0.48996
2.00000
3.99960
题意:
设C(m,n) = m! / ((m - n)! * n!),输入正整数p、q、r、s,输出C(p,q)/C(r,s)
分析:
C(p,q) / C(r,s) = p! * (r - s)! * s! / ((p - q)! * q! * r!),于是,我们采用唯一分解定理。add_integer(n,d)表示将整数n进行因数分解。add_factorial(n, d)表示将n!进行因数分解。

1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<vector> 5 #include<iostream> 6 using namespace std; 7 const int maxn = 10000; 8 vector<int> primes; 9 int e[maxn]; 10 // 乘以或除以n. d=0表示乘,d=-1表示除 11 void add_integer(int n, int d) { 12 for(int i = 0; i < primes.size(); i++) { 13 while(n % primes[i] == 0) { 14 n /= primes[i]; 15 e[i] += d; 16 } 17 if(n == 1) break; // 提前终止循环,节约时间 18 } 19 } 20 21 void add_factorial(int n, int d) { 22 for(int i = 1; i <= n; i++) 23 add_integer(i, d); 24 } 25 26 bool is_prime(int n) { 27 int m = floor(sqrt(n) + 0.5); 28 for(int a = 2; a <= m; a++) 29 if(n % a == 0) return false; 30 return true; 31 } 32 int main() { 33 for(int i = 2; i <= 10000; i++) 34 if(is_prime(i)) primes.push_back(i); 35 int p, q, r, s; 36 while(cin >> p >> q >> r >> s) { 37 memset(e, 0, sizeof(e)); 38 add_factorial(p, 1); 39 add_factorial(q, -1); 40 add_factorial(p-q, -1); 41 add_factorial(r, -1); 42 add_factorial(s, 1); 43 add_factorial(r-s, 1); 44 double ans = 1; 45 for(int i = 0; i < primes.size(); i++) 46 ans *= pow(primes[i], e[i]); 47 printf("%.5lf\n", ans); 48 } 49 return 0; 50 }