| Algorithm isPrime |
Algorithm isPrime
//read a single value from the user and print whether it is prime
//prompt and read pp (potential prime)
print "enter potential prime > 1: "
read pp
//initialize pd
pd = 2
//check for potential divisors of pp
while(pp % pd != 0)
pd++
//print result
if(pp == pd)
print pp, " is prime. "
else
print pp, " is composite. "
fi
//alternate way to print
//print pp, ((pp == pd) ? "is prime " : "is composite")
End .
enter n > 1 (c-d to exit): 5 5 is prime enter n > 1 (c-d to exit): 4 4 is composite enter n > 1 (c-d to exit): ^d exiting . .w1/isPrime-eof.cpp
/* isPrime() ---------------------------------------------- * returns true iff n is prime */ int isPrime(long n);
../w5/isPrime-fn1.h --header
file
../w5/isPrime-fn2.h
--header file
../w5/isPrime-v3.cpp
--client (#includes one of the header files)
enter n > 1 (c-d to exit): 5 first prime greater than 5 is 7 enter n > 1 (c-d to exit): 11 first prime greater than 11 is 13 enter n > 1 (c-d to exit): ^d exiting . .
enter n > 1 (c-d to exit): 2 first 2 primes: 2 3 enter n > 1 (c-d to exit): 5 first 5 primes: 2 3 5 7 11 enter n > 1 (c-d to exit): ^d exiting . .
enter n > 1 (c-d to exit): 2 sum of the first 2 primes: 5 enter n > 1 (c-d to exit): 5 sum of the first 5 primes: 28 enter n > 1 (c-d to exit): ^d exiting . .
% primeTest < prime.in >! prime.out