C++ Find Greatest Common Factor
Posted by Samath
Last Updated: January 05, 2017
  917

The greatest common factor, or GCF, is the greatest factor that divides two numbers. To find the GCF of two numbers:
1. List the prime factors of each number.
2. Multiply those factors both numbers have in common. If there are no common prime factors, the GCF is 1.

#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char const *argv[])
{
  int _gcf = 1;
  int a = 30, b = 24;

  
  int f = a, g = b;
	

	while( true )
	{
		if(f % g == 0) {
			_gcf = (f > g) ? g : f;
			break;
		}

		f = (f > g) ? f : g;
		g = (f > g) ? f % g : g % f;
	}

	cout << "The Greatest Common Factor of " << a;
	cout << " and " << b;
	cout << " is " << _gcf;

	cin.get();
	return 0;
}