Lexington High School Mathematics Math Dept. Front Page  | Student Links  | Family Links 
Introduction to C++, Kevin Kelly Kelly Front Page  | C++ Course Guide | C++ Assignments | C++ Info

Assignment 22: Prime function

due Thursday 4/11

A positive integer n is called prime if it is not divisible by any positive integers other than 1 and n. For example, 7 is prime but 8 is not prime.

Write a function prime that returns true if a positive integer is prime, and returns false otherwise. For example, prime(7) should return true and prime(8) should return false.

Here is one strategy you could use for checking that a number is prime. (If you can think of a more efficient strategy you can use that instead.) To find out whether n is prime, you just need to check whether it is divisible by any of the numbers in between 1 and n. For example, to see whether 7 is prime, check whether it is divisible by 2, 3, 4, 5, or 6. (You will need a loop in your program to successively check each of these numbers.) Since it turns out that 7 is not divisible by any of these numbers, 7 is prime.

Your prime function must utilize the divisible function that you wrote for Assignment 17.

As usual, you will need to write a main program that tests the prime function. The program should allow the user to type a number, then tell the user whether or not that number is prime. Use a repeating structure in your main program that allows the user to do this repeatedly, until they type the number 0 indicating that they want to stop.

Test values for sample run

2
10
13
49
256
2001
999983
1022117


Extensions

To earn the extension points on this assignment, make your program work as efficiently as possible, by checking as few divisors as possible. (It's possible to determine whether a number is prime without checking every smaller number as a possible divisor.)