PTA 整数的素因子分解

将正整数n分解为其素因子的乘积,其中n>=2并且在int范围内。Solution类的数据成员n代表需要分解的正整数,构造函数完成对数据成员n的初始化,声明了成员函数solve()实现对n的分解。请根据样例输出实现成员函数。注意输出时每行最后一个数字后面没有空格。

裁判测试程序样例:

#include <iostream>
#include <cmath>
using namespace std;

class Solution {
public:
    Solution(int num) {
        n = num;
    }
    void solve();//将n分解为素因子的乘积
private:
    int n;
};

int main()
{
    int n;
    while (cin >> n) {
        Solution obj(n);
        obj.solve();
    }
    return 0;
}
//你的代码将被嵌在这里

输入样例:

2
3
13
24
36
1024
65535

输出样例:

2=2
3=3
13=13
24=2*2*2*3
36=2*2*3*3
1024=2*2*2*2*2*2*2*2*2*2
65535=3*5*17*257

AC代码:

bool prime(int p)
{
	for (int div = 2; div<= sqrt(p); div++)
		if (p % div == 0) return false;
	return true;
}
void Solution::solve()
{
	cout << n << '=';
	if (prime(n)) cout << n << endl;
	else {
		for (int div = 2, judge = 0;;) {
			if (prime(div) && n % div == 0) {
				if (judge) cout << '*';
				cout << div;
				n /= div;
				judge = 1;
				if (n == 1) break;
			}
			else {
				if (judge) cout << '*';
				judge = 0;
				div++;
			}
		}
		cout << endl;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值