Answer to Question #223160 in C++ for Wildcat

Question #223160
Write a C++ program that calculates GCD of given number using function with returning by reference
1
Expert's answer
2021-08-04T04:08:07-0400
#include <iostream>


using namespace std;
//Implement function GCD return by reference (&)
int& gcd(int a, int b)
{
	/*
	gcd(a,b)
	a=b*q+r1
	b=r1*q1+r2
	........
	to rn=0
	........
	Example
	gcd(18,12)
	18=12*1+6
	12=6*1+0
	gcd=6
	*/
	while (a != 0 && b != 0)
	{
		if (a > b)
			a %= b;
		else
			b %= a;
	}
	int ans = a + b;
	return ans;
}
int main()
{
	cout << "Enter numbers: ";
	int a, b;
	cin >> a >> b;
	int gc = gcd(a, b);
	cout << "GCD=" << gc << endl;
	return  0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS