#include <iostream> using namespace std; bool isPrime(int n){ if(n%2==0) return false; int m=3; while(m*m<n){ if(n%m==0) return false; m += 2; } return true; } int main(){ int input; cout<<"Please enter an integer: "; cin>>input; if(isPrime(input)) cout<<input<<" is a prime number.\n"; else cout<<input<<" is not a prime number.\n"; return 0; }

Solution

First of all, we need to know exactly what a prime number is. By definition, a prime number is an integer which is not evenly divisible by any integer except 1 and itself, with the exception that 1 is not a prime number. Therefore, the first several prime numbers are 2, 3, 5, 7, 11, 13.

This concept should make it obvious that the first bug in this program is that it thinks 1 is a prime number. Also,

Finally, we would like to know what the program thinks about perfect squares such as 9, 14, and 25. The while loop in

For example, 9 is a prime; however, the while loop fails when m equals 3 (thus returns true). This should not happen, so we should change < to <=.

Here is the corrected program:

#include <iostream> using namespace std; bool isPrime(int n){ if(n==2) return true; if(n%2==0 || n==1) return false; int m=3; while(m*m<=n){ if(n%m==0) return false; m += 2; } return true; } int main(){ int input; cout<<"Please enter an integer: "; cin>>input; if(isPrime(input)) cout<<input<<" is a prime number.\n"; else cout<<input<<" is not a prime number.\n"; return 0; }By examining this exercise, you should have learned that a correctly working function is crucial for the correctness of a program. In this example there is only one function.

What if you want to do more to the prime number the user enters? You write more functions to process the number, and you end up getting incorrect results but are at a loss to figure out where they originate. Therefore, testing a function individually helps programmers locate a bug, if any.

Also, correct logic is crucial to writing a good function. In this case, if we knew exactly what numbers are prime, we probably would not have made any mistakes.

Next let’s look at a buggy program to find its bugs!

◀ Trap 5 - The cin Operator▶ Trap 7 - Factorial