Ninja has been given an assignment by his teacher. He has been given three integers ‘a’,’b’, and ‘c’ which represent the coefficients of the equation “ax + by = c”. His task is to find the initial integral solution of the given equation if a finite solution exists.
For example:
If ‘a’, ‘b’, and ‘c’ are 5, 10, and 10 respectively, the initial integral solution will be 2 and 0 for ‘x’ and ‘y’ respectively.
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.
The first line of each test case contains three space-separated integers ‘a’, ‘b’, and ‘c’.
Output Format:
For each case, you need to return an array containing the value of both x and y if a finite solution exists. In case, there exists no finite solution, you can return -1 for both x and y.
The output of each test case will be printed in a separate line.
Note:
You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= a <= 100000
1 <= b <= 100000
1 <= c <= 100000
Time Limit: 1 sec
2
5 10 10
12 43 97
2 0
1746 -485
Test case 1:
For the first test case of sample output 1, for ‘a’, ‘b’ and ‘c’ as 4, 18 and 10, we get finite solution as -20 and 5 for x and y respectively.
Test case 2:
For the second test case of sample output 1, for ‘a’, ‘b’ and ‘c’ as 12, 43 and 97, we get a finite solution as 1746 and -485 for x and y respectively.
1
4 6 1
-1 -1
Test case 1:
For the first test case of sample output 1, for ‘a’, ‘b’ and ‘c’ as 4, 6 and 1, we get no solution. Hence, we receive -1 and -1 for x and y respectively.
Can Extended Euclidean Algorithm help us?
Here, we can use the extended euclidean algorithm which helps us to find the solution of a linear equation using the greatest common divisor(gcd) of the coefficients of x and y. Using this gcd, if this gcd is a divisor of ‘c’, then we can find the solution for the equation ‘ax + by = c’.
O(log(max(a, b))) where ‘a’ and ‘b’ are the coefficients of ‘x’ and ‘y’ respectively.
Here, we can use a function that calculates the gcd of ‘a’ and ‘b’. The gcd function has a time complexity of O(log(max( a, b))). Hence our time complexity is O(log(max(a, b))).
O(1)
As we have used some constant variables, Hence our space complexity is O(1).