題目描述
n!表示n的階乘,並且有n!=1×2x…×n成立。求n!中有多少個質因子p。
這個問題是什麼意思呢?舉個例子,6!=1×2×3×4×5×6,於是6!中有4個質因子2,因爲2、4、6中各有1個2、2個2、1個2;而6!中有兩個質因子3,因爲3、6中均各有1個3。
解題思路:
遍歷1~n中的每個數字,各個數字有多少個p因子,然後加起來即可
//求n!中有多少個質因子p
int cal(int n, int p) {
int result = 0;
for (int i = 2; i <= n; i++) {
int temp = i;
while (temp % p == 0)
{
result++;
temp /= p;
}
}
return result;
}
第二種解法:
此方法摘抄自算法筆記
代碼如下:
//求n!中有多少個質因子p
int cal(int n, int p) {
int result = 0;
while (n) {
result += n / p;//累加 n / p^k
n /= p;//相當於分母多乘了一個p
}
return result;
}
組合數的計算
計算組合數C(n,m)
下圖來自於算法筆記
代碼:
//組合數的計算
long long C(long long n, long long m) {
if (m == 0 || m == n) {
return 1;
}
return C(n - 1, m) + C(n - 1, m - 1);
}