最小公因數c++
在C++中,你可以使用標準庫中的 std::gcd
函數來計算兩個數字的最大公因數(Greatest Common Divisor, GCD)。這個函數在 <numeric>
標頭中定義,它是通過 std::numeric_limits<>
類模板提供的。
以下是一個簡單的例子,展示了如何使用 std::gcd
來找出兩個數字的GCD:
#include <iostream>
#include <numeric> // 包含 std::gcd
int main() {
int a = 40;
int b = 30;
// 使用 std::gcd 計算 GCD
int gcd = std::gcd(a, b);
// 輸出 GCD
std::cout << "The GCD of " << a << " and " << b << " is " << gcd << std::endl;
return 0;
}
輸出:
The GCD of 40 and 30 is 10
如果你想要自己實現最小公因數(Greatest Common Divisor, GCD)算法,可以使用埃拉托斯特尼質數篩(Eratosthenes's sieve)或者更簡單的輾轉相除法( Euclidean algorithm )。以下是一個使用輾轉相除法的GCD算法的例子:
#include <iostream>
// 輾轉相除法計算 GCD
int gcd(int a, int b) {
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int main() {
int a = 40;
int b = 30;
// 使用輾轉相除法計算 GCD
int gcd = gcd(a, b);
// 輸出 GCD
std::cout << "The GCD of " << a << " and " << b << " is " << gcd << std::endl;
return 0;
}
這個算法的時間複雜度為O(log(max(a, b))),其中max(a, b)
是兩個數字中較大的一個。