题目链接:点击打开链接
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1 * p2^k2 *…*pm^km.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi's are prime factors of N in increasing order, and the exponent ki is the number of pi -- hence when there is only one pi, ki is 1 and must NOT be printed out.
Sample Input:97532468Sample Output:
97532468=2^2*11*17*101*1291我的C++代码:
#include<iostream>
#include<cmath>
using namespace std;
bool prime(int value)//若value是素数,返回1,不是返回0.
{
int i = 2;
if (value == 0 || value == 1)//素数是一个大于1的自然数,不包括0 1
{
return false;
}
for (; i <= sqrt(value); i++)
{
if (value%i == 0)
{
return false;
}
}
return true;
}
int main()
{
int i=0,n;
cin >> n;
cout << n << "=";
if (n==1)
{
cout <<n;
}
else
{
for (i = 2; i <= n; i++)
{
int exp = 0;//因子的指数
if (prime(i))//因子是素数
{
while (n%i == 0)//分解求指数
{
exp++;
n = n / i;
}
}
if (exp >= 2)//输出指数>=2的因子及指数
cout <<i<< "^" << exp;
else if (exp==1)//指数等于1只输出因子
cout <<i;
if (n != 1 && exp >= 1)//exp >= 1表示有素因子时才输出*号
cout << '*';
else if (n == 1)//全部分解,退出
break;
}
}
//system("pause");
return 0;
}