CSCI 3300
Spring 2009
Exercises for Quiz 3

  1. You are given a function prime(n) that takes an integer n and returns true if n is prime, false if n is not prime. Write a C++ definition of function sumPrimes(n) that produces the sum of all of the prime numbers from 2 to n. For example, sumPrimes(4) = 2 + 3 = 5 and sumPrimes(11) = 2 + 3 + 5 + 7 + 11 = 28. Write this function using a loop, not using recursion.

    Answer

  2. Rewrite the definition of sumPrimes of the preceding question using recursion, without a loop.

    Answer

  3. Using the prime function, write a C++ definition of function anyPrime(a,b) that returns true if any of the numbers from a up to b are prime. For example, anyPrime(4,6) is true because there is at least one prime number (namely 5) among 4, 5, 6. anyprime(5,5) is also true, but anyprime(14,16) is false since none of 14, 15 or 16 is prime. Also anyprime(6,4) is false because the range of numbers (from 6 up to 4) is empty.

    Write this definition using a loop, not using recursion.

    Answer

  4. Write the definition of function anyPrime from the preceding question using recursion, not using a loop.

    Answer

  5. You are given a function next(n), which takes an integer and produces an integer. You do not know exactly what next does, but you can use it. Given a starting value i, function next defines an implicit sequence i, next(i), next(next(i)), ..., 0. (The sequence stops at 0. next(0) is undefined.)

    Write a C++ definition of a function called firstBig that takes parameter i and produces the first value in the implicit sequence that starts with i that is greater than 100, or returns 0 if there is no such value.

    For example, if the sequence starting at 5 is (5, 41, 22, 84, 19, 102, 105, 91, 8, 0) then firstBig(5) = 102.

    Write this function definition with a loop. Do not use recursion.

    Answer

  6. Write a definition of function firstBig of the preceding question using recursion. Do not use any kind of loop for this version.

    Answer