1、穷举算法 时间复杂度(O(n))
// 从小到大public static int gcd(int m, int n) { int gcd = 1; for (int i = 2; i <= m && i <= n; i++) { if (m % i == 0 && n % i == 0) { gcd = i; } } return gcd; }
// 从大到小public static int gcd(int m, int n) {
int gcd = 1; for (int i = n; i >= 1; i--) { if (m % i == 0 && n % i == 0) { gcd = i; break; } } return gcd; }
// 穷举算法 数字n的除数不可能比n/2大public static int gcd(int m, int n) { int gcd = 1; if (m % n == 0) { return n; } for (int i = n / 2; i >= 1; i--) { if (m % i == 0 && n % i == 0) { gcd = i; break; } } return gcd; }
2、递归 时间复杂度(O(logn))
public static int gcd(int m, int n) { if (m % n == 0) { return n; } else { return gcd(n, m % n); } }
3、while循环 时间复杂度(O(logn))
public static int gcd(int m, int n) { int remainder = m % n; while (remainder > 0) { m = n; n = remainder; remainder = m % n; } return n; }
时间: 2024-11-19 06:32:47