0
点赞
收藏
分享

微信扫一扫

PAT 1059 Prime Factors (素数筛)

雷亚荣 2023-03-02 阅读 109


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 ​​=​​​ p​1​​​^​​​k​1​​​*​​​p​2​​​^​​​k​2​​​*​​​…​​*​​​p​m​​​^​​k​m​​, where p​i​​'s are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ -- hence when there is only one p​i​​, k​i​​ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

97532468=2^2*11*17*101*1291

之前写的这个题很像,好像写过很多次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;
}

 

举报

相关推荐

0 条评论