简体   繁体   中英

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.

#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)

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 . b being a/2 , that's never going to cause a match.

That means your loop ending condition that would return 1 is never true.

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. Clang gave a warning, without any special flags:

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:

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 :

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; at the beginning.

Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.

For example:-

 If a = 11

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

So you are running loop till 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

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 . 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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