欧拉计划53题

/**
* Combinatoric selections
* Problem 53
*
* There are exactly ten ways of selecting three from five, 12345:
* 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
*
* In combinatorics, we use the notation, 5C3 = 10.
* In general,nCr = n!/(r!(n−r)!),
* where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
*
* It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
*
* How many, not necessarily distinct,
* values of  nCr, for 1 ≤ n ≤ 100,
* are greater than one-million?
*
*
*/
题目,求nCr>1000000的个数?其中 1 ≤ n ≤ 100

分析:
由nCr的定义可得,
100C1 = 100C99
100C2 = 100C98
是完全对称的
由于n!增长速度很快,所以不建议按定义来计算,非常容易溢出
观察
100C1 = 100;
100C2 = 100 * 99 / 2;
100C3 = 100C2 * 98 / 3;
100C4 = 100C3 * 97 / 4;
容易判断的100Cr是逐渐递增的,在r<50的情况下
因此,当算到第一个大于1000000的数,即可停止计算
以n = 100为例
100C4 = 3921225 > 1000000,
因此当r= 4到96都满足条件,共有93个数
循环100 到 1,即可求出所有满足条件的数的个数

代码实现
int count = 0;

for (int n = 100; n > 1; n--){

int temp = 1;
for (int i = 1; i < n / 2; i++){
temp = temp * (n - i + 1) / i;
if (temp > 1000000){
count += (n - 2 * i + 1);
break;
}
}
}


结果:4075






















猜你喜欢

转载自535260620.iteye.com/blog/2286480