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 .

Exercises

  1. Translate the above algorithm into a c++ program, isPrime-v1.cpp.

    isPrime-v1.cpp

  2. Modify isPrime-v1.cpp by adding an EOF-controlled while loop to generate this I/O interface:
    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

  3. Write a c++ function that meets this specification:

    /* isPrime() ----------------------------------------------
     * returns true iff n is prime */
    int isPrime(long n);
    

    Remember: Functions do not use cin and do not use cout. The function returns a value to the caller (main(), for example), and the caller will handle I/O.

    Modify isPrime-v1.cpp so that main() calls function isPrime().

    ../w4/isPrime-v2.cpp

  4. Function definitions can be placed in their own header file and then #included in a client program. Example:

    ../w5/isPrime-fn1.h      --header file
    ../w5/isPrime-fn2.h      --header file
    ../w5/isPrime-v3.cpp   --client (#includes one of the header files)

  5. Write a pseudocode algorithm to meet this I/O spec:
    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 . .
    

  6. Write a pseudocode algorithm to meet this I/O spec:
    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 . .
    

  7. Write a pseudocode algorithm to meet this I/O spec:
    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 . .
    

  8. Example: use Unix I/O redirection to run primeTest:

            % primeTest < prime.in >! prime.out