算法 - 求兩個自然數的最小公倍數(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
*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM