Given two positive integers X and K, the task is to find all possible pair of integers (A, B) such that the difference between the pair of integers raised to the power K is the given integer X. If there exists no such pair, then print “-1”.
Note: The value of K is at least 5 and X is at most 1018.
Input: X = 33, K = 5
Explanation: All the possible pairs are as follows:
- (1, -2): The value of (15 – (-2)5) = 33, which is equal to X(= 33).
- (2, -1): The value of (25 – (-1)5) = 33, which is equal to X(= 33).
Therefore, the total number of pairs are 2.
Input: X = 10, K = 5
Approach: The given problem can be solved based on the observation that the maximum possible value of X can be 1018. Therefore, the value of the pair of integers (A, B) will lie over the range [-1000, 1000]. Follow the steps below to solve the problem:
- Initialize a variable, say count as 0, to count the number of pairs that satisfies the given conditions.
- Generate all possible pairs (A, B) over the range [-1000, 1000] and if the value of (AK – BK) is X, then print the corresponding pair and increment count by 1.
- After completing the above steps, if the value of count is 0, then print “-1”.
Below is the implementation of the above approach:
1 -2 2 -1
Time Complexity: O(2000 * 2000)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.