1059 Prime Factors (25 分)
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1×p2k2×⋯×pmkm.
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<stdio.h>
#include<math.h>
int isPrime(int n)
{
int i,flag=1;
if(n==0 || n==1) flag=0;
for(i=2;i<sqrt(n);i++){
if(n%2==0){
flag=0;
break;
}
}
return flag;
}
int main()
{
int n,i,j,cnt=0;
scanf("%d",&n);
printf("%d=",n);
int first=0;
if(n==1)
printf("%d",1);
for(i=2;i<=sqrt(n);i++){
if(isPrime(i)){
while(n%i==0){
n/=i;
cnt++;
}
if(cnt>1){
if(first) printf("*");
printf("%d^%d",i,cnt);
first=1;}
if(cnt==1){
if(first) printf("*");
printf("%d",i);
first=1;
}
cnt=0;
}
}
if(isPrime(n)){
if(first) printf("*");
printf("%d",n);
}}