方法一:
遍历1~
n
n
n,求出每个数包含几个质因子
p
p
p,然后再相加即可。
时间复杂度为:
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)。
代码如下:
int cal(int n, int p){
int ans = 0;
for(int i = 2; i <= n; i++){ //遍历2~n
int temp = i;
while(temp % p == 0){ //temp是p的倍数
ans++; //个数加1
temp /= p;
}
}
}
方法二:
依据
n
!
n!
n!中有
(
n
p
+
n
p
2
+
n
p
3
+
⋯
)
(\frac {n}{p}+\frac {n}{p^2}+\frac {n}{p^3}+\cdots)
(pn+p2n+p3n+⋯)个质因子
p
p
p,其中除法均向下取整,便可得到另一算法。
时间复杂度为:
O
(
l
o
g
n
)
O(logn)
O(logn)。
代码如下:
int cal(int n, int p){
int ans = 0;
while(n){
ans += n / p; //累加n / p^k
n /= p; //相当于分母多乘一个p
}
}
方法三:
基于事实:
n
!
n!
n!中质因子
p
p
p的个数,实际上等于1~
n
n
n中
p
p
p的倍数的个数
n
p
\frac {n}{p}
pn再加上
n
p
!
\frac {n}{p}!
pn!中质因子
p
p
p的个数。
以
10
!
10!
10!中质因子2的个数为例:
10
!
=
1
×
2
×
3
×
⋯
×
10
=
2
×
4
×
6
×
8
×
10
×
(
1
×
3
×
5
×
7
×
9
)
=
2
5
×
1
×
2
×
3
×
4
×
5
×
(
1
×
3
×
5
×
7
×
9
)
=
2
5
×
5
!
×
(
1
×
3
×
5
×
7
×
9
)
5
!
=
1
×
2
×
3
×
4
×
5
=
2
×
4
×
(
1
×
3
×
5
)
=
2
2
×
1
×
2
×
(
1
×
3
×
5
)
=
2
2
×
2
!
×
(
1
×
3
×
5
)
2
!
=
1
×
2
=
2
×
1
=
2
1
×
(
1
)
\begin{aligned} 10! &=1\times2\times3\times\cdots \times10\\ &=2\times4\times6\times8\times10\times(1\times3\times5\times7\times9)\\ &=2^5\times1\times2\times3\times4\times5\times(1\times3\times5\times7\times9)\\ &=2^5\times5!\times(1\times3\times5\times7\times9)\\ 5! &=1\times2\times3\times4\times5\\ &=2\times4\times(1\times3\times5)\\ &=2^2\times1\times2\times(1\times3\times5)\\ &=2^2\times2!\times(1\times3\times5)\\ 2! &=1\times2\\ &=2\times1\\ &=2^1\times(1) \end{aligned}
10!5!2!=1×2×3×⋯×10=2×4×6×8×10×(1×3×5×7×9)=25×1×2×3×4×5×(1×3×5×7×9)=25×5!×(1×3×5×7×9)=1×2×3×4×5=2×4×(1×3×5)=22×1×2×(1×3×5)=22×2!×(1×3×5)=1×2=2×1=21×(1) 故
10
!
10!
10!中质因子2的个数为
5
+
2
+
1
=
8
5+2+1=8
5+2+1=8个。
递归代码如下:
int cal(int n, int p){
if(n < p) return 0; //n小于p时不再有质因子p
return n / p + cal(n / p, p); //返回n/p的个数加上(n/p)!中质因子p的个数
}
参考资料
[1]. 《算法笔记》P181-183