ProgrammingHardTCS NQT · Cognizant GenC Next

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer fact[10], count = 0, s, n
fact[0] = 1
for (each i from 1 to 9)
    fact[i] = fact[i - 1] * i
end for
for (each x from 1 to 1000)
    s = 0
    n = x
    while (n > 0)
        s = s + fact[n mod 10]
        n = n / 10
    end while
    if (s == x)
        count = count + 1
    end if
end for
Print count
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 4

Correct answer: C. 3

The loop counts numbers equal to the sum of the factorials of their digits: 1 (1!), 2 (2!) and 145 (1! + 4! + 5! = 1 + 24 + 120). count = 3; the next one, 40585, is beyond 1000.

More Pseudocode and Code Tracing questions

Exams that ask this topic