将正整数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;
}
}