Revised Version: C++ program to check whether a number is prime or not

About two days ago, I published a post namely C++ program to check whether a number is prime or not. One of my kind readers, Jaume commented on that program and gave me some very useful suggestions and tips on improving it. I am very thankful to him for taking the time to improve my understanding. So, here is a revised version of this program. Changes made in this revision include:

  • Use of a while loop instead of the if statement to validate input numbers and accept only non negative integers.
  • Type of the variable decider has been changed from int to bool and a not operator is used to change its value instead of the increment operator.
  • Variable counter has been started from 3 instead of 2 and is incremented by 2 instead of one during each loop and devision by 2 has been made a special case.
  • and … some minor improvements in the prompts given using cout statements.

Source code of this revised program is given below.

If you also have any suggestions about improving this program a little further then please share them with me via comments. I shall be very thankful to you!

// Prime Checker.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;

int _tmain()
{
	int number; // number entered by the user to check
	int counter = 3; // counter to check the entered number against all other numbers
	bool decider = true; //it will deside whether number is prime or not ...

	cout << "Please enter the number that you want to check:n";
	cin >> number;

	while (number < 0)
	{
		cout << "Please enter a positive integer:n";
		cin >> number;
	}
	if (number == 0 || number == 1)
	{
		cout << number << " is neither a prime nor a composite number.n";
	}
	else if (number % 2 == 0)
	{
		cout << number << " is not a prime number. It is a composite number instead...n";
		cout << endl;
		decider = !(decider);
	}
	else
	{
		while (counter < number)
		{
			if (number % counter == 0)
			{
				cout << number << " is not a prime number. It is a composite number instead...n";
				decider = !(decider);
				break;
			}
			counter = counter + 2;
		}
		if (decider)
		{
			cout << number << " is a prime number.n";
		}
	}

	cout << "Press any key to close this program ...";
	_getch();
	return 0;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Responses on this post

  1. “counter” only needs to go up to the Sqrt of number.

    Why would you say
    decider = !decider
    when you could say
    decider = false?
    Your version is more dangerous, as it depends the initial/last value and is less clear.