#46094: cpp 超級簡單解


1121232@stu.wghs.tp.edu.tw (Ian911436)

學校 : 臺北市私立薇閣高級中學
編號 : 258883
來源 : [60.248.154.143]
最後登入時間 :
2025-05-14 15:36:23
a007. 判斷質數 | From: [60.248.154.143] | 發表日期 : 2025-05-21 15:29

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int g[100000];  // 質數表
    int t = 0;      // 質數數量

    // 建立質數表
    for (int i = 2; i <= 100000; i++) {
        bool b = true;
        for (int j = 2; j <= sqrt(i); j++) {
            if (i % j == 0) {
                b = false;
                break;
            }
        }
        if (b) {
            g[t++] = i;
        }
    }

    int n;
    while (cin >> n) {
        bool b = true;
        int sq = sqrt(n);
        for (int i = 0; i < t; i++) {
            if (g[i] > sq) break;
            if (n % g[i] == 0) {
                b = false;
                break;
            }
        }

        if (b)
            cout << "質數" << endl;
        else
            cout << "非質數" << endl;
    }

    return 0;
}

 
ZeroJudge Forum