P1075 [NOIP2012 普及组] 质因数分解

题目传送门

一、原始解法

#include <bits/stdc++.h>

using namespace std;

//判断一个数是不是质数
bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i <= n / i; i++)
        if (n % i == 0) return false;
    return true;
}

int main() {
    int n;
    cin >> n;
    for (int i = 2; i <= n / i; i++)
        if (n % i == 0 && isPrime(i) && isPrime(n / i)) {
            cout << n / i;
            break;
        }
    return 0;
}

二、玄学解法

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    cin >> n;
    for (int i = 2; i <= n / i; i++)
        if (n % i == 0) {
            cout << n / i;
            break;
        }
    return 0;
}

三、筛质数解法

#include <bits/stdc++.h>

using namespace std;
const int N = 44721+10;

//欧拉筛
int primes[N], cnt;     // primes[]存储所有素数
bool st[N];             // st[x]存储x是否被筛掉
void get_primes(int n) {
    for (int i = 2; i <= n; i++) {
        if (!st[i]) primes[cnt++] = i;
        for (int j = 0; primes[j] <= n / i; j++) {
            st[primes[j] * i] = true;
            if (i % primes[j] == 0) break;
        }
    }
}

int main() {
    int n;
    cin >> n;
    get_primes(sqrt(n));
    for (int i = 0; i < cnt; i++) {
        if (n % primes[i] == 0) {
            cout << n / primes[i] << endl;
            break;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15575687.html