📜  C++程序检查素数

📅  最后修改于: 2021-05-28 04:26:15             🧑  作者: Mango

给定正整数,请检查数字是否为质数。质数是大于1的自然数,除1及其本身外,没有其他除数。前几个素数的示例是{2、3、5

例子:

Input:  n = 11
Output: true

Input:  n = 15
Output: false

Input:  n = 1
Output: false
// A school method based C++ program to check if a
// number is prime
#include 
using namespace std;
  
bool isPrime(int n)
{
    // Corner case
    if (n <= 1)
        return false;
  
    // Check from 2 to n-1
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;
  
    return true;
}
  
// Driver Program to test above function
int main()
{
    isPrime(11) ? cout << " true\n" : cout << " false\n";
    isPrime(15) ? cout << " true\n" : cout << " false\n";
    return 0;
}
输出:
true
 false

该解决方案的时间复杂度为O(n)

优化学校方法

// A optimized school method based C++ program to check
// if a number is prime
#include 
using namespace std;
  
bool isPrime(int n)
{
    // Corner cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
  
    // This is checked so that we can skip
    // middle five numbers in below loop
    if (n % 2 == 0 || n % 3 == 0)
        return false;
  
    for (int i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
  
    return true;
}
  
// Driver Program to test above function
int main()
{
    isPrime(11) ? cout << " true\n" : cout << " false\n";
    isPrime(15) ? cout << " true\n" : cout << " false\n";
    return 0;
}
输出:
true
 false

请参考有关Primality Test的完整文章。设置1(简介和学校方法)以了解更多详细信息!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。