A 1059 Prime Factors
Problem Description
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
Each input file contains one test case which gives a positive integer N in the range of long int.
Output
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
题目大意:
质因数分解
解题思路:
先找出10000以内的所有质数,然后用n不断去÷这些质数,分解到最后如果n大于1,说明n有一个大于10000的质因数,再输出这个质因数。特判n=1的情况
AC代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int maxn = 10005;
ll prime[maxn],n;
int num[maxn],ind=0,cnt=0;
bool isprime(ll x){
if(x<=1) return false;
const int len = (int)sqrt(1.0*x);
for(int i=2;i<=len;i++){
if(x%i==0) return false;
}
return true;
}
void getprime(){
for(ll i=2;i<10000;i++){
if(isprime(i)){
prime[ind++]=i;
}
}
}
int main(){
getprime();
memset(num,0,sizeof(num));
scanf("%lld",&n);
printf("%lld=",n);
if(n==1){
printf("1");
return 0;
}
for(int i=0;i<ind;i++){
ll temp=prime[i];
while(n>1){
if(n%temp==0){
num[i]++;
n/=temp;
}else{
break;
}
}
}
for(int i=0;i<ind;i++){
if(num[i]>0){
if(cnt>0) printf("*");
printf("%lld",prime[i]);
if(num[i]>1) printf("^%d",num[i]);
cnt++;
}
}
if(n>1){
printf("*%lld",n);
}
return 0;
}