算法 - 求兩個天然數的最小公倍數(C++)

//****************************************************************************************************
//
//  求兩個天然數的最小公倍數 - C++ - by Chimomo
//
//  最小公倍數 = 兩數的乘積 / 最大公約數
//
//****************************************************************************************************

#include <iostream>
#include <cassert>
#include <stack>
#include <math.h>

using namespace std ;

int GreatestCommonDivisor(int a, int b)
{
	int temp;

	if(a < b)
	{
		// 交換兩個數。使大數放在a的位置上。
		temp = a;
		a = b;
		b = temp;
	}

	while(b != 0)
	{
		// 利用展轉相除法,直到b爲0爲止。
		temp = a % b;
		a = b;
		b = temp;
	}

	return a;
}

int LeastCommonMultiple(int a, int b)
{
	int temp = a * b / GreatestCommonDivisor(a, b);
	return temp;
}

int main()
{
	cout << LeastCommonMultiple(318, 87632) << endl;
	return 0;
}

// Output:
/*
13933488
*/
相關文章
相關標籤/搜索