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!

Join the Conversation

3 Comments

Leave a Reply

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

  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.

%d bloggers like this: