In: Computer Science
In C++
The greatest common divisor (GCD) of two integers in the largest integer that evenly divides each of the numbers. Write a function called GCD that has a void return type, and accepts 3 parameters (first two by value, third by reference). The function should find the greatest common divisor of the first two numbers, and have the result as its OUTGOING value.
Write a main function that asks the users for two integers, and uses your function to find the greatest common divisor and then prints that value out.
Code:
#include<iostream>
using namespace std;
void GCD(int x,int y,int &OUTGOING);
int main(){
int x,y,OUTGOING;
cout<<"Enter first number:";
cin>>x;
cout<<"Enter second number:";
cin>>y;
GCD(x,y,OUTGOING);
cout<<"GCD is "<<OUTGOING;
}
void GCD(int x,int y,int &OUTGOING){
if(x<0){
x=-x;
}
if(y<0){
y=-y;
}
if(x==0){
OUTGOING=y;
}
else if(y==0){
OUTGOING=x;
}
else{
while(x!=y){
if(x>y){
x=x-y;
}
else{
y=y-x;
}
}
OUTGOING=y;
}
}
Output: