求兩個數的最大公約數
在數學中,最大公約數 (GCD) 是能同時整除兩個整數的最大可能整數。條件是這些整數必須是非零的。
我們將按照歐幾里得演算法來求兩個數的 GCD。
輸入和輸出
Input: Two numbers 51 and 34 Output: The GCD is: 17
演算法
findGCD(a, b)
輸入:兩個數 a 和 b。
輸出:a 和 b 的 GCD。
Begin if a = 0 OR b = 0, then return 0 if a = b, then return b if a > b, then return findGCD(a-b, b) else return findGCD(a, b-a) End
示例
#include<iostream>
using namespace std;
int findGCD(int a, int b) { //assume a is greater than b
if(a == 0 || b == 0)
return 0; //as a and b are 0, the greatest divisior is also 0
if(a==b)
return b; //when both numbers are same
if(a>b)
return findGCD(a-b, b);
else
return findGCD(a, b-a);
}
int main() {
int a, b;
cout << "Enter Two numbers to find GCD: "; cin >> a >> b;
cout << "The GCD is: " << findGCD(a,b);
}輸出
Enter Two numbers to find GCD: 51 34 The GCD is: 17
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP