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
這道題跟:https://blog.csdn.net/qq_40046426/article/details/78917021 之前寫的這個題很像,好像寫過很多次zhe'zhon
需要注意的是測試點3:1 不是素數,因爲我剛開始寫的沒有考慮 1 所以 測試點 3 一直過不去 特判一下就好了
#include <bits/stdc++.h>
#define ll long long
#define Max 1110000
using namespace std;
map<ll,int> cnt; //prime的次數
bool isprime[Max];
int prime[Max];
ll a;
int isPrime(ll a){
if(a == 1) return 0;
for(int i = 2; i <= sqrt(a); i++){
if(a % i == 0) return 0;
}
return 1;
}
void getPrime(){
int ind = 0;
memset(isprime, true, sizeof(isprime));
for(int i = 2; i <= 1000000; i++){
if(isprime[i]){
prime[ind++] = i;
}
for(int j = 0; j < ind && prime[j] * i <= 1000000; j++){
isprime[prime[j] * i] = false;
if(i % prime[j] == 0) {
break;
}
}
}
}
int main(){
set<ll> s;
s.clear(); cnt.clear();
getPrime();
cin >> a;
if(isPrime(a)) {
cout << a << "=" << a << endl;
}else{
cout << a << "=";
int ind = 0;
ll temp = a;
while(true){
if(temp % prime[ind] == 0) {
temp /= prime[ind];
s.insert(prime[ind]);
cnt[prime[ind]]++;
}else {
ind++;
}
if(temp == 1) break;
}
if(a == 1) {
s.insert(1);
cnt[1]++;
}
int num = s.size();
// cout << "--->: " << num << endl;
set<ll>::iterator it;
for(it = s.begin(); it != s.end(); it++){
if(cnt[(*it)] >= 2) {
cout << (*it) << "^" << cnt[(*it)];
}else {
cout << (*it);
}
num --;
if(num != 0) cout << "*";
}
cout << endl;
}
return 0;
}