#46094: cpp 超級簡單解


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

學校 : 臺北市私立薇閣高級中學
編號 : 258883
來源 : [60.248.154.143]
最後登入時間 :
2025-06-20 09:40:35

#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;
}

#46503: Re: cpp 超級簡單解


s032 (mmmmmmm)

學校 : 高雄市五福國中
編號 : 298924
來源 : [42.77.45.78]
最後登入時間 :
2025-10-11 17:39:20

#include
#include

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;
}

謝謝