您的位置:首页 > 其它

1059. Prime Factors (25)

2016-02-15 15:13 701 查看
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:
97532468

Sample Output:
97532468=2^2*11*17*101*1291

#include <iostream>
#include <vector>
#include <cmath>
#include <cstddef>
#include <map>
using namespace std;
long int next_prime(int n)
{
for (int i = n+1;; i++)
{
bool is_prime = true;
for (int j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
{
is_prime = false;
break;
}
}
if (is_prime == true)
{
return i;
}
}
}
int main()
{
map<int,int> primes;
long int n;
long int prime = 2;
cin >> n;
if (n == 1)
{
printf("1=1");
return 0;
}
long output = n;
while (prime <= n )
{
if (n % prime == 0)
{
primes[prime]++;
n /= prime;
}
else
{
prime = next_prime(prime);
}
}
cout << output << "=";
bool first = true;
for (auto itr = primes.begin(); itr != primes.end(); ++itr)
{
if (first == true)
{
first = false;
if (itr->second > 1)
{
printf("%d^%d", itr->first, itr->second);
}
else
{
printf("%d", itr->first);
}
}
else
{
if (itr->second > 1)
{
printf("*%d^%d", itr->first, itr->second);
}
else
{
printf("*%d", itr->first);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pat