Cob*_*les 5 java algorithm math
我正在尝试自动查找一个数字与另一个数字的最接近因子;
例子:
700 到 30 的最近因数是 28(30 不能进入 700,但 28 可以)。
一个明显的解决方案是获取 700 的所有因子并进行简单的距离计算以找到最接近 30 的因子,但这似乎效率低下。
另一种解决方案是找到所有的基本质因数,例如:
private List<Integer> getPrimeFactors(int upTo) {
List<Integer> result = new ArrayList<>();
for (int i = 2; i <= upTo; i++) {
if (upTo % i == 0) {
result.add(i);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
并将这些数字中的每一个相乘以获得所有组合,从而找到最接近的。
我正在尝试对其进行编程,使其自动化。有什么更好的解决方案吗?
我的解决方案包含在一个小的静态方法中:
/**
* @param target the number you want the factor to be close to
* @param number the number you want the result to be a factor of
*/
private static int getClosestFactor(int target, int number) {
for (int i = 0; i < number; i++) {
if (number % (target + i) == 0) {
return target + i;
} else if (number % (target - i) == 0) {
return target - i;
}
}
return number;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3455 次 |
| 最近记录: |