17A. Recursive Scan Algorithms

We have seen how to write scan algorithms using loops. Anything you can do with a loop, you can also do with recursion. A preceding page included a definition of sum(A, n). Here are some additional examples.


Largest

Let's define function largest(A, n), which returns the largest value among the first n values in array A, where n > 0. Be sure to remember that the first n variables in array A are A[0], … A[n − 1].

If n = 1, there is only one value, A[0], to consider. That one must be the largest.

If n > 1 then the largest value must either be the last one, A[n −1], or it must come before the last one. Compute m = largest(A, n − 1), the largest of the first n − 1 values in A. Then the largest of the first n values in A must either be m or A[n − 1], whichever one is larger.

  // largest(A,n) returns the largest of A[0],...,A[n-1].
  //
  // It is required that n > 0.

  int largest(const int A[], const int n)
  {
    if(n == 1)
    {
      return A[0];
    }
    else
    {
      const int m = largest(A, n-1);
      return max(m, A[n-1]);
    }
  }

SumPrimes

Here is an implementation of sumPrimes(n), which returns the sum of the prime numbers that are less than or equal to n. (We implemented sumPrimes previously using a loop.)

Because we need to add up prime numbers only, there is one more case than in sum or largest. Since the smallest prime number is 2, sumPrimes(n) = 0 when n < 2. Otherwise, compute m = sumPrimes(n − 1). If n is not prime, then sumPrimes(n) = m. If n is prime, sumPrimes(n) = m + n.

  //==============================================
  // 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)
  {
    if(n < 2)
    {
      return 0;
    }
    else 
    {
      const int m = sumPrimes(n-1);
      if(isPrime(n))
      {
        return m + n;
      }
      else
      {
        return m;
      }
    }
  }

Exercises

  1. Using recursion, write a definition of sumsq(n), which returns 12 + 22 + … n2. Answer

  2. Write a recursive definition of function numPrimes(n), which returns a count of how many of 1, …, n are prime. Answer