1. 程式人生 > >演算法 - 求兩個自然數的最小公倍數(C++)

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

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!希望你也加入到我們人工智慧的隊伍中來!http://www.captainbed.net