Ctrl K

Sums of Two Powers

Medium
You are given integers a, b and limit. Find every integer not greater than limit that can be written as a^i + b^j for some integers i ≥ 0 and j ≥ 0. Each such number must appear in the answer exactly once, even if it can be formed in several ways. The numbers may be returned in any order.
Example 1
a=2, b=5, limit=12 → [2, 3, 5, 6, 7, 9]

2 = 1 + 1, 3 = 2 + 1, 5 = 4 + 1, 6 = 1 + 5, 7 = 2 + 5, 9 = 8 + 1 = 4 + 5. The sum 9 can be made two ways but appears in the answer once.

Example 2
a=1, b=4, limit=20 → [17, 2, 5]

Every power of 1 is 1, so only 1 + 1, 1 + 4 and 1 + 16 qualify.

Example 3
a=7, b=3, limit=1 → []
Constraints
  • 1 ≤ a, b ≤ 100
  • 0 ≤ limit ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShuffle the Digits Into a Power of Two MediumGrid Points Under Circles MediumEven Vowel and Consonant Pieces MediumPrimes Along Grid Rays MediumBalanced Quadruples With Gaps Medium
loading Python…
Input
a=2, b=5, limit=12
Expected
[2, 3, 5, 6, 7, 9]

Run checks the first 3 tests in your browser. Submit checks all 85 tests on the server, hidden ones included.