标签:
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; }
标签:
原文地址:http://www.cnblogs.com/diyishijian/p/5076962.html