找到彼此最接近的单个数字的两个最高因子

时间:2016-11-20 03:12:42

标签: numbers

36-> 6 * 6(不是9 * 4)

40-> 5 * 8(不是10 * 4)

35-> 7 * 5 等

我猜是这样的:

candidate = input.square_root.round_to_nearest_int; 
while (true){
test = input/candidate;
 if (test.is_integer) return; 
else 
candidate.decrement;
}

1 个答案:

答案 0 :(得分:1)

你的方法确实有效。

如果n = ab然后a <= sqrt(n) <= b,那么如果选择a,b以使b-a最小化,则a是{n的最大除数1}}小于或等于平方根。我对伪代码的唯一调整是检查余数并查看它是否为零,而不是检查商是否为整数。像(在Python中)的东西:

import math

def closestDivisors(n):
    a = round(math.sqrt(n))
    while n%a > 0: a -= 1
    return a,n//a

例如,

>>> closestDivisors(36)
(6, 6)
>>> closestDivisors(40)
(5, 8)
>>> closestDivisors(1000003)
(1, 1000003)

(因为最后一次输入是素数)。