C++ code for MyProgrammingLab The greatest common divisor of integers x and y is
ID: 3725125 • Letter: C
Question
C++ code for MyProgrammingLab
The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd that returns the greatest common divisor of x and y, defined recursively as follows: * If y is equal to 0, then gcd(x,y) is x; * Otherwise, gcd(x,y) is gcd(y,x%y) where % is the modulus operator. Write a test program that prompts the user to enter two integers and then calculates and outputs their greatest common divisor using your recursive function. Note: in order for this algorithm to work, x must be greater than y; if the value user enters for y is greater than x, your program will have to swap them.
Explanation / Answer
Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.
//Code.cpp
#include<iostream>
using namespace std;
//method to calculate and return the GCD of two numbers
int gcd(int x, int y){
//if y is 0, gcd of (x,y)=x
if(y==0){
return x;
}else{
//otherwise, gcd of (x,y)= gcd of (y,x%y)
return gcd(y,x%y);
}
}
int main(){
//defining two variables
int x,y;
//prompting and receiving two numbers
cout<<"Enter two numbers : ";
cin>>x;
cin>>y;
//displaying the gcd
if(x>y){
//if x > y, invoking the method as gcd(x,y)
cout<<"GCD : "<<gcd(x,y);
}else{
//if x > y, invoking the method as gcd(y,x) [swapped]
cout<<"GCD : "<<gcd(y,x);
}
return 0;
}
/*OUTPUT*/
Enter two numbers : 400 350
GCD : 50
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.