2787. Ways to Express an Integer as Sum of Powers #2043
-
Topics: Given two positive integers Return the number of ways Since the result can be very large, return it modulo For example, if Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of ways a given positive integer Approach
Let's implement this solution in PHP: 2787. Ways to Express an Integer as Sum of Powers <?php
/**
* @param Integer $n
* @param Integer $x
* @return Integer
*/
function numberOfWays($n, $x) {
$mod = 1000000007;
$dp = array_fill(0, $n + 1, 0);
$dp[0] = 1;
$max_i = 1;
while (pow($max_i, $x) <= $n) {
$max_i++;
}
$max_i--;
for ($i = 1; $i <= $max_i; $i++) {
$v = (int)pow($i, $x);
for ($j = $n; $j >= $v; $j--) {
$dp[$j] = ($dp[$j] + $dp[$j - $v]) % $mod;
}
}
return $dp[$n] % $mod;
}
// Test cases
echo numberOfWays(10, 2) . "\n"; // Output: 1
echo numberOfWays(4, 1) . "\n"; // Output: 2
?> Explanation:
This approach efficiently counts all unique combinations of integers raised to the |
Beta Was this translation helpful? Give feedback.
We need to count the number of ways a given positive integer
n
can be expressed as the sum of unique positive integers each raised to thex
-th power. The solution involves dynamic programming to efficiently compute the number of valid combinations without repetition.Approach
x
-th power equalsn
. The solution must avoid duplicate sets (e.g.,{1, 2}
and{2, 1}
are considered the same set) and each integer can be used at most once.dp
wheredp[j]
represents the number of ways to achieve the sumj
us…