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:97532468Sample Output:
97532468=2^2*11*17*101*1291
大意是将一个long int型整数进行质因子分解
解题思路:
1.打质数表
2.将所给整数m按照质数表从小到大的顺序相除,每个质数都除到不能除为止,用结构体记录相应质数和除的次数
3.输出
坑:
1.等于1的时候是特例,得特殊处理
2.注意最后得到的1不能输出
代码(long long和int用混了,不管了反正ac了)
#include<cmath>
#include<time.h>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
#define MAX 100000000
LL prime[10000];
int count = 0;
bool is_prime[MAX] = {0};
void get_prime(int maxn){
memset(is_prime,0,sizeof(bool)*maxn);
for(int i=2;i<maxn;i++){
if(!is_prime[i]){
prime[count++] = i;
for(int j=i+i;j<maxn;j += i){
is_prime[j] = true;
}
}
}
}
int main(){
LL mm,m;
scanf("%lld",&mm);
if(mm == 1){
printf("1=1");
return 0;
}
m = mm;
LL m_sqrt = sqrt(m*1.0);
get_prime(m_sqrt);
struct ans{
LL prime;
int num;
}ans[10];
int ans_c = 0;
LL i=0;
while(i<count){
if(m%prime[i]==0){
ans[ans_c].prime = prime[i];
ans[ans_c].num = 1;
m = m/prime[i];
while(m%prime[i]==0){
m = m/prime[i];
ans[ans_c].num++;
}
ans_c++;
}
i++;
}
if(m!=1){
ans[ans_c].prime = m;
ans[ans_c++].num = 1;
}
printf("%lld=",mm);
for(i=0;i<ans_c;i++){
if(i>0) printf("*");
if(ans[i].num!=0){
if(ans[i].num == 1){
printf("%lld",ans[i].prime);
}else{
printf("%lld^%d",ans[i].prime,ans[i].num);
}
}
}
}