Ways to Express an Integer as Sum of Powers - Problem

Given two positive integers n and x.

Return the number of ways n can be expressed as the sum of the xth power of unique positive integers, in other words, the number of sets of unique integers [n1, n2, ..., nk] where n = n1^x + n2^x + ... + nk^x.

Since the result can be very large, return it modulo 10^9 + 7.

Example: If n = 160 and x = 3, one way to express n is n = 2^3 + 3^3 + 5^3.

Input & Output

Example 1 — Basic Case
$ Input: n = 10, x = 2
Output: 1
💡 Note: Only one way: 10 = 1² + 3² = 1 + 9. We use unique positive integers 1 and 3.
Example 2 — Multiple Ways
$ Input: n = 4, x = 1
Output: 5
💡 Note: Two ways to express 4 as sum of unique positive integers to power 1: {4} gives 4¹=4, and {1,3} gives 1¹+3¹=1+3=4.
Example 3 — Larger Input
$ Input: n = 160, x = 3
Output: 1
💡 Note: One way to express 160 as sum of unique cubes: 2³ + 3³ + 5³ = 8 + 27 + 125 = 160.

Constraints

  • 1 ≤ n ≤ 300
  • 1 ≤ x ≤ 5

Visualization

Tap to expand
Ways to Express Integer as Sum of Powers INPUT n = 10 x = 2 Find ways to express 10 as sum of squares (unique) Available Squares: 1²=1 2²=4 3²=9 4²=16 (too big) Combinations to Check: 1 + 9 = 10 OK 1 + 4 = 5 X 4 + 9 = 13 X ALGORITHM STEPS 1 Generate Powers Collect i^x where i^x <= n 2 DP Table Setup dp[j] = ways to make sum j 3 Process Each Power Update dp backwards 4 Return dp[n] Modulo 10^9 + 7 DP Table (subset sum): 1 0 1 1 ... ... 1 9 1 10 dp[10] = 1 (only {1,9}) dp[j] += dp[j - power] FINAL RESULT Valid Decomposition Found: 10 = 1² + 3² = 1 + 9 Visual Breakdown: 1 + 9 Output: 1 Only one valid way! Key Insight: This is a subset sum variant using 0/1 knapsack DP. Each power i^x can be used at most once. Process powers in reverse order (n down to power) to avoid counting duplicates. Time: O(n * n^(1/x)) | Space: O(n) | Use modulo to handle large results. TutorialsPoint - Ways to Express an Integer as Sum of Powers | Optimal Solution (0/1 Knapsack DP)
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen