您的位置:首页 > 其它

几个基本数学问题

2014-09-17 17:11 274 查看
分解质因数

求最大公约数

求最小公倍数

牛顿迭代求平方根

分解质因数

import java.util.ArrayList;
import java.util.List;

public class Solution {

// 返回质因数分解
List<Integer> getPrimeFactors(int n) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
// 注意while的终止条件是n!=i
while (n != i) {
if (n % i == 0) {
list.add(i);
n = n / i;
} else
break;
}
}
list.add(n);
return list;

}

public static void main(String[] args) {
System.out.println(new Solution().getPrimeFactors(120));

}
}


求最大公约数

public class Solution {
/**
* 辗转相除法 缺点:对于大整数求模是瓶颈
*/
public int gcd1(int x, int y) {
return y == 0 ? x : gcd1(y, x % y);
}

/**
* 更相减损术 缺点:某些case下递归次数太多,不如gcd(100000,1)的情况。
*/
public int gcd2(int x, int y) {
if (x < y)
return gcd2(y, x);
if (y == 0)
return x;
else
return gcd2(x - y, y);

}

/**
* 编程之美上的方法,避免了以上两种方法的劣势, 复杂度O(log(max(x,y)));
*/
public int gcd(int x, int y) {
if (x < y)
return gcd(y, x);
if (y == 0)
return x;
else {
if (isEven(x)) {
if (isEven(y)) {
return gcd(x >> 1, y >> 1) << 1;
} else {
return gcd(x >> 1, y);
}

} else {
if (isEven(y)) {
return gcd(x, y >> 1);
} else {
return gcd(y, x - y);
}

}

}

}

private boolean isEven(int x) {
return (x & 1) == 0;
}

public static void main(String[] args) {
int a = 420000, b = 3050;
System.out.println(new Solution().gcd1(a, b));
System.out.println(new Solution().gcd2(a, b));
System.out.println(new Solution().gcd(a, b));

}
}


求最小公倍数

x*y/gcd(x,y);

牛顿迭代求平方根

/article/1424416.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: