c++自动确定素数

c++ automatically determien prime numbers

本文关键字:c++      更新时间:2023-10-16

我正试图在c++中找出如何找到一个范围内的所有素数(目前使用100(

我不关心性能,我从c++开始,并试图从我的书中理解这个程序练习。我在下面尝试使用我的程序,但它一直返回false。有什么想法吗?我已经阅读了几乎所有谷歌/bing的帮助以及堆栈溢出。我可以为它编写代码,以便输入数字;只是没有循环通过所有数字

你知道我做错了什么吗?

#include <iostream>
using namespace std;
bool isPrime(long n);
int main() 
{
    int i;
    //some vars
    char emptyVar;
    //first loop (to increment the number)
    for (i = 0; i <= 100; i++)
    {
        //checking all numbers below 100
        if (isPrime(i) == true)
        {
            //is true
            cout << i << ", ";
        }
        else if (isPrime(i) == false)
        {
            //is false
            cout <<"false , ";
        }
    }
    cin >> emptyVar;
}
bool isPrime(long n)
{
    long i =0;
    //checks to see if the number is a prime
    for (i = 2; i < n; i++) // sqrt is the highest possible factor
    {
        if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
        {
            // is a factor and not prime
            return false;
        }
        else if (n % i != 0 && i >= 100)
        {
            //is not a factor
            return true;
        }
    }
}

函数isPrime没有针对每个可能的执行路径的return语句。例如,当n == 2时,isPrime做什么?

以下是for循环的工作原理(在伪代码中(。一般语法为

for (initialiazion; condition; increment) {
   body;
}
rest;

这可以转换为while循环:

initialiazion;
while (condition) {
  body;
  increment;
}
rest;

特别地,在执行body之前,紧接在intialization之后检查condition

我怀疑,你认为for循环是这样工作的:

initialiazion;
do {
  body;
  increment;
} while (condition);
rest;

即在第一个CCD_ 11之后检查条件。但事实并非如此。

如果它不是每个i的一个因子,而不仅仅是它遇到的第一个因子,那么它应该返回true。

bool isPrime(long n)
{
    long i =0;
    //checks to see if the number is a prime
    for (i = 2; i < n ; i++) // sqrt is the highest possible factor
    {
        if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
        {
            // is a factor and not prime
            return false;
        }
    }
    return true; 

}

此外,在您的情况下,搜索i>n/2以外的内容是没有意义的。当然,你应该看看文献,这些都是真正稳健的素性测试算法。

您的isPrime函数不正确。它应该检查所有号码,然后才检查return true;

这个块永远不会在你的输入中调用:

    else if (n % i != 0 && i >= 100)
    {
        //is not a factor
        return true;
    }
相关文章:
  • 没有找到相关文章