top1编程
← 返回题目
题解

【入门】素数的个数

1 条题解

  • 0
    @ 2026-7-30 0:50:41

    解题思路

    按照题目要求直接计算。代码中使用简单的循环、判断和数组,把每一步写出来,方便理解。

    参考代码

    // 读取题目给出的数据。
    // 按照题意完成计算。
    // 输出最终答案。
    #include <iostream>
    using namespace std;
    int main() {
        int m, n, cnt = 0;
        cin >> m >> n;
        for (int i = m; i <= n; i++) {
            if (i < 2) continue;
            bool ok = true;
            for (int j = 2; j * j <= i; j++) {
                if (i % j == 0) ok = false;
            }
            if (ok) cnt++;
        }
        cout << cnt << endl;
        return 0;
    }
    

    复杂度

    代码只使用了题目需要的循环、判断和数组。若有 n 次循环,时间复杂度为 O(n);只使用固定数量变量时,空间复杂度为 O(1)。

    • 1