Find the final X and Y when they are Altering under given condition in C++

C++Server Side ProgrammingProgramming

Consider we have the initial values of two positive integers X and Y. Find the final value of X and Y, such that there will be some alteration as mentioned below −

  • step1 − If X = 0 and Y = 0 then terminate the process, otherwise go to step2

  • step2 − If X >= 2Y, then set X = X – 2Y, and go to step1, otherwise go to step3

  • step3 − If Y >= 2X, then set Y = Y – 2X, and go to step1, otherwise end the process.

The number X and Y will be in range [0 and 1018] So we can use the Brute Force approach.

Example

#include<iostream>
using namespace std;
void alterNumber(long long x, long long y) {
   while (1) {
      if (x == 0 || y == 0)
         break;
      if (x >= 2 * y)
         x = x % (2 * y);
      else if (y >= 2 * x)
         y = y % (2 * x);
      else
         break;
   }
   cout << "X: " << x << "\n" << "Y: " << y;
}
int main() {
   long long x = 12, y = 5;
   alterNumber(x, y);
}

Output

X: 0
Y: 1
raja
Published on 04-Nov-2019 07:45:37
Advertisements