求n!中有多少个质因子p

方法一:

  遍历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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

D-A-X

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值