简体   繁体   中英

Prime number finding program using bool values

I am trying to write a program in C++ that, given a data file that includes random integers, identifies each integer as prime or not prime, and counts the integers. Here is what I have so far:

#include <iostream>
using namespace std;
int main()
    {
  int number;  //number to be tested
  int  count = 0;  //count of integers in file
  cin >> number;
  while (cin)
    {
      bool prime = true;
  if (number <= 0)
    {
      prime = false;
    }
  else
    {
      for (int i=2; i<number; i++)
      if (number % i == 0)
         { 
           prime = false;
           break;
         }
    }

  if (prime = true)
        cout << number << " is a prime number." << endl;
  if (prime = false)
        cout << number << " is not a prime number." << endl;
  cin >> number;  
  count++;
 } 
cout << "The file contains " << count << " integers" << endl;
return 0;
}

The program compiles, but finds all values in a data set as not prime. Here is what I got as output from a data file:

24 is a prime number.
13 is a prime number.
18 is a prime number.
-25 is a prime number.
42 is a prime number.
0 is a prime number.
2 is a prime number.
The file contains 7 integers

Any suggestions? Am I using the bool values correctly? Thank you

You are using the assignment operator = instead of the equality comparison operator == when checking if prime is true or false. (You should also use braces for your for loop.)

Heads up that you can check the factors until prime/2 (or sqrt(prime) , see below) since nothing greater than half of a number can be a factor of it!

This line:

if (prime = true)
        cout << number << " is a prime number." << endl;

is assigning "true" to variable "prime". As a expression, an assignment operation returns the value being assigned, so the expression inside the if evaluates as true and hence, prints that the number is prime.

You have to change = by == . An old trick to avoid these mistakes is to change the sentence as this:

if (true = prime)
        cout << number << " is a prime number." << endl;

Then the compiler had warned you about the obvious error.

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