使用 C++ 判断质数

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,你将学习如何编写一个 C++ 程序来检查给定的数字是否为质数。质数是指只能被 1 和其自身整除的数字。它是数论中的一个重要概念,并在密码学中有许多重要应用。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/variables -.-> lab-96177{{"`使用 C++ 判断质数`"}} cpp/conditions -.-> lab-96177{{"`使用 C++ 判断质数`"}} cpp/for_loop -.-> lab-96177{{"`使用 C++ 判断质数`"}} cpp/output -.-> lab-96177{{"`使用 C++ 判断质数`"}} cpp/user_input -.-> lab-96177{{"`使用 C++ 判断质数`"}} cpp/files -.-> lab-96177{{"`使用 C++ 判断质数`"}} cpp/code_formatting -.-> lab-96177{{"`使用 C++ 判断质数`"}} end

创建一个新的 C++ 源文件

首先,在 ~/project/ 目录下创建一个名为 main.cpp 的 C++ 源文件。

cd ~/project
touch main.cpp

编写 C++ 程序检查质数

将以下代码复制到 main.cpp 文件中:

#include <iostream>

using namespace std;

int main() {
    int n, i;
    bool isPrime = true;

    // 从用户获取数字
    cout << "Enter a positive integer: ";
    cin >> n;

    // 检查数字是否为质数
    for(i=2; i<=n/2; i++) {
        if(n%i == 0) {
            isPrime = false;
            break;
        }
    }

    if(isPrime) {
        cout << n << " is a prime number." << endl;
    } else {
        cout << n << " is not a prime number." << endl;
    }

    return 0;
}

该程序从用户获取一个整数 n,并检查它是否为质数。如果是质数,则输出 n is a prime number.;否则输出 n is not a prime number.

编译并运行程序

在 Ubuntu 系统中打开终端,并导航到 ~/project/ 目录:

cd ~/project

通过运行以下命令编译 main.cpp 代码:

g++ main.cpp -o main

通过执行以下命令运行编译后的可执行文件:

./main

测试程序

现在,输入不同的数字来检查它们是否为质数:

Enter a positive integer: 17
17 is a prime number.
Enter a positive integer: 57
57 is not a prime number.

总结

在本实验中,你学习了如何编写一个 C++ 程序来检查给定的数字是否为质数。你现在对这一概念有了扎实的理解,这在数论和密码学中非常重要。

您可能感兴趣的其他 C++ 教程