13B. Filtered Scans

Sometimes you want accumulate information concerning selected values in a sequence. To do that, just scan through the sequence, but skip over values that are not of interest in the loop body.

The following function illustrates. Like the previous examples, it has an integer parameter n, which is thought of as representing sequence [1, 2, 3, …, n]. However, since 1 is not prime, we start at 2 instead.

Predicate isPrime(n) is assumed to return true just when n is prime.

  // sumPrimes(n) yields the sum of the prime
  // numbers that are less than or equal to n.
  // For example, sumPrimes(5) = 2 + 3 + 5 = 10.

  int sumPrimes(const int n)
  {
    int total = 0;
    for(int i = 2; i <= n; i++)
    {
      if(isPrime(i))
      {
        total += i;
      }
    }
    return total;
  }

Exercises

  1. Write a C++ definition of function numPerfect(n), which returns a count of the numbers from 1 to n that are perfect. For example, 6 is the smallest perfect integer, so numPerfect(6) should return 1.

    Make n have type int. Use function isPerfect from an earlier exercise. Use a for-loop.

    Answer

  2. You are given a function isGood that takes a parameter of type int and returns a result of type bool that is either true or false.

    Say that an integer n is good if isGood(n) returns true. You do not need to know what isGood does to complete this exercise.

    Write a C++ definition of function numGood(a, b) that returns a count of the number of good values k such that a ≤ ka.

    Notice that numGood(5, 4) = 0; there are no numbers k so that 5 ≤ k ≤ 4, so there are certainly no good ones.

    Answer