Write a c program to compute GCD of two positive numbers?

The largest positive integer which divides two or more integers without any remainder is called Greatest Common Divisor. greatest common divisor of two positive numbers by Euclid’s Algorithm: let m and n be two positive integers then below is the steps to compute gcd.

Let m=20 and n=298
m = 2*2*5
n = 2*149

Here 2 is largest common digit which divides both m and n , so 2 is gcd of 20 and 298.

Here is sample code in c++.

#include<iostream>
using namespace std;
class GCD {
	int m, n;
	int result;
public:
	GCD() {
		m = 20;
		n = 298;
	}
	void compute(); //function to find gcg
	void printResult();

};
void GCD::compute() {
	while (m != n) {
		if (m > n)
			m = m - n;
		else
			n = n - m;
	}
	result = m;
}

void GCD::printResult() {
	cout << result << endl;
}
int main() {
	GCD gcd;
	gcd.compute();
	gcd.printResult();
	return 0;
}

Recursive solution of c program to compute gcd of two positive numbers

#include<iostream>
using namespace std;

int gcd(int a, int b) {
	if (b == 0)
		return a;

	gcd(b, a % b);
}

int main() {
	int a = 20;
	int b = 298;
	cout << gcd(a, b);
	return 0;
}

 



Related Contents to follow