Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the largest prime factor of 2^20 - 1? Run the code.

Problem: What is the largest prime factor of 2^20 - 1? Run the code.
n = 2 ** 20 - 1
f = 2
last = 1
while f * f <= n:
    while n % f == 0:
        last = f
        n //= f
    f += 1
if n > 1:
    last = n
print(last)
What is printed?
  1. A. 31
  2. B. 5
  3. C. 41
  4. D. 1048575

Correct answer: C. 41

2²⁰ − 1 = 3 · 5² · 11 · 31 · 41. Trial division stops when f² exceeds the reduced n, so forgetting the final if n > 1 step returns 31; 5 is the repeated factor, and 1048575 is n itself.

More Coding Interview Problems questions

Exams that ask this topic