Programming Basics (Pseudocode Tracing)

÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. When the following function pow is called as pow(2, 10), how many times is pow called, including the first call?

○integer: pow(integer: x, integer: n)
  if (n = 0)
    return 1
  endif
  integer: h ← pow(x, n ÷ 2)
  if (n mod 2 = 0)
    return h × h
  endif
  return h × h × x
  1. A5
  2. B10
  3. C11
Show answer and explanation

Answer: A. 5

pow(x, n) computes x to the power n by squaring the result of pow(x, n ÷ 2) with n halved (multiplying by x once more when n is odd). n changes to 10, 5, 2, 1 and 0, and the recursion stops at n = 0, so pow is called 5 times. The return value is 2¹⁰ = 1024. Decreasing n by 1 at a time, as in x × pow(x, n − 1), would make 11 calls, from n = 10 down to 0. Halving n makes the number of calls grow roughly in proportion to log₂ n.

  • A. Correct. n = 10, 5, 2, 1, 0: five calls.
  • B. This is the exponent n = 10. n is halved, not decreased by 1.
  • C. This is the number of calls when n decreases by 1 each time (x × pow(x, n − 1)).
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. What does the following function s return when called as s(7)?
  2. When the following procedure p is called as p(3), what sequence of values is output?
  3. What does the following function fib return when called as fib(10)?
  4. When the following function c is called as c(4, 2), how many times is c called, including the first call?
  5. ⊕ is bitwise exclusive OR. What are the values of x and y after the following program runs?