文章

79

粉丝

221

获赞

45

访问

165.5k

头像
分解质因数的个数
P1156 清华大学上机题
发布于2023年3月22日 20:27
阅读数 2.7k

#include <iostream>
#include <cmath>
using namespace std;
bool Jud(int a) {
	if (a <= 1)
		return false;
	if (a == 2)
		return true;
	for (int i = 2; i < sqrt(a) + 1; i++)
		if (a % i == 0)
			return false;
	return true;
}
int Cou(int n) {
	int res = 0,i=2;
	while(n > 1){
		if(Jud(n)){
			res++;
			break;
		}
		if(n % i == 0){
			n/=i;
			res++;
		}
		else
			i++;
	}
	return res;
}
int main() {
	int n;
	while (cin >> n)
		cout << Cou(n) << endl;
	return 0;
}

思路:

定理:任何数都可分解为若干个质数的乘积。

由定理,则对待处理数字n每次判断数字i是否为它的因子,若是则与其相除,商作为下轮的待处理数字同时因子数量res自增,若i非待处理数字n的因子则i自增,若某轮发现待处理数字n自己就是质数,则无需对其因子判断,直接因子数量res自增同时退出循环,可大大减少算法运行时间。

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发