
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Final X and Y in C++ Under Given Conditions
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
Advertisements