简体   繁体   English

素数C ++程序

[英]Prime number C++ program

I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is. 我不确定是否应该在这里询问程序员,还是我应该问程序员,但是我一直在试图弄清为什么该程序无法运行,尽管我发现了一些错误,但即使返回x也不是素数。

#include <iostream>
using namespace std;


  bool primetest(int a) {
 int i;
 //Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
 int b = a / 2;
 //Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
 for (i = 2; i < b; i++) {
     //If  the user input has no remainder then it cannot be a prime and the loop can stop (break)
     if (a % i == 0) {
           return(0);
           break;
     }
     //Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
              else if ((a % i != 0) && (i == a -1)) {
          return (1);
          break;
     }
 }   
}

 int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
                   cout << user << " is a prime number.";
}
else  {
      cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}

Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?) 抱歉,如果它太本地化(在这种情况下,您可以建议我在哪里问这样的具体问题?)

I should add that I am VERY new to C++ (and programming in general) 我应该补充一点,我对C ++(和一般的编程)非常陌生

This was simply intended to be a test of functions and controls. 这仅仅是为了测试功能和控件。

i can never be equal to a - 1 - you're only going up to b - 1 . i永远不会等于a - 1你只会上升到b - 1 b being a/2 , that's never going to cause a match. ba/2 ,永远不会导致匹配。

That means your loop ending condition that would return 1 is never true. 这意味着将返回1的循环结束条件永远不会成立。

In the case of a prime number, you run off the end of the loop. 如果是质数,则循环结束。 That causes undefined behaviour, since you don't have a return statement there. 这会导致不确定的行为,因为那里没有return语句。 Clang gave a warning, without any special flags: Clang发出了警告,没有任何特殊标志:

example.cpp:22:1: warning: control may reach end of non-void function
      [-Wreturn-type]
}
^
1 warning generated.

If your compiler didn't warn you, you need to turn on some more warning flags. 如果您的编译器没有警告您,则需要打开更多警告标志。 For example, adding -Wall gives a warning when using GCC: 例如,添加-Wall会在使用GCC时发出警告:

example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function

Overall, your prime-checking loop is much more complicated than it needs to be. 总体而言,素数检查循环要复杂得多。 Assuming you only care about values of a greater than or equal to 2 : 假设你只关心的值a大于或等于2

bool primetest(int a)
{
    int b = sqrt(a); // only need to test up to the square root of the input

    for (int i = 2; i <= b; i++)
    {
        if (a % i == 0)
           return false;
   }

   // if the loop completed, a is prime
   return true;
}

If you want to handle all int values, you can just add an if (a < 2) return false; 如果要处理所有int值,则可以添加if (a < 2) return false; at the beginning. 一开始。

Your logic is incorrect. 您的逻辑不正确。 You are using this expression (i == a -1)) which can never be true as Carl said. 您正在使用此表达式(i == a -1)) ,就像卡尔所说的那样,它永远不可能是正确的。

For example:- 例如:-

 If a = 11

 b = a/2 = 5  (Fractional part truncated)

So you are running loop till i<5 . 因此,您正在循环运行直到i<5 So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10 所以i永远不能等于a-1因为在这种情况下i的最大值将是4而a-1值将是10

You can do this by just checking till square root. 您只需检查直到平方根即可。 But below is some modification to your code to make it work. 但是下面是对代码的一些修改,以使其正常工作。

#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
 //If  the user input has no remainder then it cannot be a prime and the loop can stop (break)
 if (a % i == 0) {
       return(0);

 }
}
//this return invokes only when it doesn't has factor
return 1;   
}

int main(void) {
  int user;
  cout << "Enter a number to test if it is a prime or not: ";
  cin >> user;
  if (primetest(user)) {
               cout << user << " is a prime number.";
  }
  else  {
     cout << user<< " is not a prime number.";
  }

return 0;

} }

check this out: 看一下这个:

//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;

int main()
{
int a = 2;       //start from 2
long long int b = 1000;     //ends at 1000

for (int i = a; i <= b; i++)
{

 for (int j = 2; j <= i; j++)
 {
    if (!(i%j)&&(i!=j))    //Condition for not prime
        {
            break;
        }

    if (j==i)             //condition for Prime Numbers
        {
              cout << i << endl;

        }
 }
}
}
main()
{
    int i,j,x,box;
    for (i=10;i<=99;i++)
    {
        box=0;
        x=i/2;
        for (j=2;j<=x;j++)
            if (i%j==0) box++;
        if (box==0) cout<<i<<" is a prime number";
        else cout<<i<<" is a composite number";
        cout<<"\n";
        getch();
    }
}

Here is the complete solution for the Finding Prime numbers till any user entered number. 这是查找素数直到所有用户输入的数字的完整解决方案。

#include <iostream.h>
#include <conio.h>
using namespace std;

main() 
{
 int num, i, countFactors;
 int a;
 cout << "Enter number " << endl;
 cin >> a;

 for (num = 1; num <= a; num++)
 {
  countFactors = 0;
  for (i = 2; i <= num; i++)
  {
   //if a factor exists from 2 up to the number, count Factors
   if (num % i == 0)
   {
    countFactors++;    
   }
  }

  //a prime number has only itself as a factor
  if (countFactors == 1)
  {
   cout << num << ", ";
  }
 }

 getch();
}

One way is to use a Sieving algorithm, such as the sieve of Eratosthenes . 一种方法是使用筛选算法,例如Eratosthenes筛选器 This is a very fast method that works exceptionally well. 这是一种非常有效的快速方法。

bool isPrime(int number){
  if(number == 2 || number == 3 | number == 5 || number == 7) return true;
  return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM