CSCI 116

Project #4: Testing Primes

 

 

Purpose: To get experience using selection and repetition statements.

 

Assignment: Write a program that asks the user for a number.  Your program should then echo the number and print out whether or not it is prime.  (A natural number is prime if it has no divisors other than itself and one.)  If it is not prime, it should print out that it is even, or print out the smallest prime divisor of the number.  Your program should loop until the user enters a 0 (zero) at which time it should exit.  Here is a sample of what the output for your program should look like:

 

Please enter a number: 7

7 is prime!

Please enter next number (0 to quit): 8

8 is even and so not prime.

Please enter next number (0 to quit): 26

26 is even and so not prime.

Please enter next number (0 to quit): 39

39 is divisible by 3

Please enter next number (0 to quit): 403

403 is divisible by 13

Please enter next number (0 to quit): 81

81 is divisible by 3

Please enter next number (0 to quit): 0

 

Programming Style: Your program should follow all the style guidelines given in the first programming assignment.

 

Getting Started: A natural number is prime if it has no divisors except for itself and one.  One way to test for primality is to successively divide a number by all numbers smaller than it and greater than one.  If any division has a zero remainder, then the number is not prime.  However, if each such division has a nonzero remainder, then the number is prime.  You can speed up testing by testing for divisibility by 2 and odd numbers only (Why? You should explain this in your comments if implement this).  Also, you only need to test divisibility with numbers up through the square root of the number (again, why?  Explain it in comments if you implement this). 

 

Turn in: You should turn in a listing of your program, with the output it generates for a sample run included as comments at the end of the source file.

 

Good luck and have fun!