【题目描述】输入一个数,输出其素因子分解表达式。 【输入】输入一个整数 n (2≤n<100)。 【输出】输出该整数的因子分解表达式。 表达式中各个素数从小到大排列。 如果该整数可以分解出因子a的b次方,当b大于1时,写做 a^b ;当b等于1时,则直接写成a。 【输入样例】60 【输出样例】2^2*3*5 【来源】No |
题目如上。
解法一:非递归解法:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i,x,cnt;
bool flag=true;
cin>>n;
while(n!=1)
{
for(i=2; i<=n; i++)
{
cnt=0; //用于记录幂次
if(n%i==0)
{
x=i;
cnt++;
n=n/i;
while(n%i==0)
{
cnt++;
n=n/i;
}
}
if(cnt!=0)
{
if(flag) //用于控制*的输出
flag=false;
else
cout<<"*";
cout<<x;
if(cnt!=1)
{
cout<<"^"<<cnt;
}
}
else
{
continue;
}
}
}
return 0;
}
解法二:递归解法
#include <bits/stdc++.h>
using namespace std;
bool flag=true;
int n; //注意题目中的输入数据要写成全局变量
void f()
{
if(n==1)
return ;
else
{
int cnt=0;
for(int i=2; i<=n; i++)
{
if(n%i==0)
{
cnt++;
n=n/i;
while(n%i==0)
{
cnt++;
n=n/i;
}
if(flag)
flag=false;
else
cout<<"*";
cout<<i;
if(cnt!=1)
{
cout<<"^"<<cnt;
}
f();
}
}
}
return ;
}
int main()
{
cin>>n;
f();
return 0;
}