Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p~1~\^k~1~ * p~2~\^k~2~ *…*p~m~\^k~m~.
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 = p~1~\^k~1~ * p~2~\^k~2~ *…*p~m~\^k~m~, where p~i~'s are prime factors of N in increasing order, and the exponent k~i~ is the number of p~i~ -- hence when there is only one p~i~, k~i~ is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
解答:本题应该算是水题了,只不过要注意N为1的情形。如果N>1,那么可以遍历寻找因子,题目变得简单直观。我也看了其他人的解法,还是觉得自己的解法是很优秀的,哈哈。
AC代码如下:
#include<iostream>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
typedef struct{
int val;
int count;
}prime;
int main()
{
long int N, C;
vector<prime> primes;
scanf("%d", &N);
C = N;
//如果N是1,那么直接输出结果即可。
if( N == 1)
{
printf("1=1\n"); return 0;
}
//寻找因子
for(int i = 2; i <= N; ++i)
{
prime tmp; tmp.val = i; tmp.count = 0;
while(N % i == 0 && N != 0)
{
tmp.count++;
N /= i;
}
if(tmp.count != 0) primes.push_back(tmp);
if(N == 0) break;
}
//输出结果
printf("%d=", C);
for(int i = 0; i < primes.size(); ++i)
{
if(i == 0)
{
if(primes[i].count == 1)
{
printf("%d", primes[i].val);
}
else
{
printf("%d^%d", primes[i].val, primes[i].count);
}
}
else
{
if(primes[i].count == 1)
{
printf("*%d", primes[i].val);
}
else
{
printf("*%d^%d", primes[i].val, primes[i].count);
}
}
}
return 0;
}