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 = 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<cstdio>
#include<cmath>
using namespace std;
bool prime(int a){
	int i;
	int len=sqrt(a);
	for(i=2;i<len;i++){
		if(a%i==0){
			return false;
		}
	}
	return true;
}
int main(){
	int n;
	scanf("%d",&n);
	if(n==1){
		printf("1=1\n");
		return 0;
	}
	int ncopy=n;
	int i;
	printf("%d=",n);
	for(i=2;i<=ncopy;i++){
		int in=0;
		if(prime(i)){
			while(n%i==0){
				in++;
				n/=i;
			}
		}
		if(in==1){
			printf("%d",i);
		}else if(in>1){
			printf("%d^%d",i,in);
		}
		if(n!=1&&in>=1){
			printf("*");
		}else if(n==1){
			break;
		}
	} 
	return 0;
} 

  

posted @ 2017-11-10 09:19  gaoren  阅读(173)  评论(0编辑  收藏  举报