Given initial values of two positive integers X and Y, Find the final value of X and Y according to below alterations:
1. If X=0 or Y=0, terminate the process. Else, go to step 2;
2. If X >= 2*Y, then change the value of X to X – 2*Y, and repeat step 1. Else, go to step 3;
3. If Y >= 2*X, then assign the value of Y to Y – 2*X, and repeat step 1. Else, end the process.
Constraints: 1<=X, Y<=10^18
Input: X=12, Y=5 Output: X=0, Y=1 Explanation: Initially X = 12, Y = 5 --> X = 2, Y = 5 (as X = X-2*Y) --> X = 2, Y = 1 (as Y = Y-2*X) --> X = 0, Y = 1 (as X = X-2*Y) --> Stop (as X = 0) Input: X=31, Y=12 Output: X=7, Y=12 Explanation: Initially X = 31, Y = 12 --> X = 7, Y = 12 (as X = X-2*Y) --> Stop (as (Y - 2*X) < 0)
Approach: Since the initial values of X and Y can be as high as 10^18. Simple brute force approach will not work.
If we observe carefully, the problem statement is nothing but a sort of Euclid Algorithm, where we will replace all subtractions with modulo.
- Program to find whether a no is power of two
- Program to find parity
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Find Union and Intersection of two unsorted arrays
- To find sum of two numbers without using any operator
- Find day of the week for a given date
- Given a number, find the next smallest palindrome
- Find the element that appears once
- Find the largest multiple of 2, 3 and 5
- Program to find amount of water in a given glass
- Find the maximum distance covered using n bikes
- Find if two rectangles overlap
- Find the smallest number whose digits multiply to a given number n
- Find next greater number with same set of digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.