Description
任意一个正整数可以分解成唯一的质因数的乘积,给出正整数,请计算出它的质因数分解式。
输入
每行一个正整数2<=n<=10^8。
输出
每行输出一个对应结果。使用”^”表示幂,”*”表示乘,质因子应该按从小到大的顺序输出,如果某一个质因子只有一次,那么就不要输出它的幂。
Sample Input
2
6
36
Sample Output
2
2*3
22*32
Sample Input
Sample Output
Source
ericxie
#include <stdio.h>
#include <math.h>
int main()
{
int n;
while(scanf("%d",&n)==1)//一定要有==1或者!=EOF,不然直接Output Limit Exceed
{
int i,flag=1;//flag是做标记
for(i=2;i<=sqrt(n);i++)//sqrt()函数是开平方根
{
if(n%i==0)//如果能取余为0
{
if(flag)//flag==1
{
flag=0;
}
else//flag==0
{
printf("*");//最开始是先输出数字的,所以先把flag变为0,之后再输出*
}
printf("%d",i);//输出i
int count=0;//计数器
while(n%i==0)//判断是否可以有幂函数
{
count++;
n/=i;//n值变化
}
if(count>1)//输出^count
{
printf("^%d",count);
}
}
}
if(n>1)//如果n大于0
{
if(flag)//说明最初始的n为素数,flag在前面的for循环没有改变
{
printf("%d",n);//直接输出素数
}
else//flag已经为0,此刻的n为for循环后剩下的变化的,现在也是素数
{
printf("*%d",n);
}
}
printf("\n");//换行
}
return 0;
}
写于2021年8月16日19:07分。