【发布时间】:2016-05-02 15:32:52
【问题描述】:
我最近遇到了一个返回给定数字的最小因子的方法:
public static int findFactor(int n)
{
int i = 1;
int j = n - 1;
int p = j; // invariant: p = i * j
while(p != n && i < j)
{
i++;
p += j;
while(p > n)
{
j--;
p -= i;
}
}
return p == n ? i : n;
}
在检查了该方法之后,我已经能够(很可能是错误地)确定了一些变量分别代表的数量:
n = the int that is subject to factorization for
the purposes of determining its smallest factor
i = the next potential factor of n to be tested
j = the smallest integer which i can be multiplied by to yield a value >= n
问题是我不知道p 代表什么数量。内部循环似乎将(p+=j) - n 视为
i 的潜在倍数,但鉴于我相信 j 所代表的,我不明白这怎么可能是真的
对于所有i,或者外循环如何解释执行的内循环的“额外”迭代
在后者因p < n而终止之前
假设我已正确确定n、i 和j 代表什么,那么p 代表什么数量?
如果我的任何决定不正确,每个数量代表什么?
【问题讨论】:
标签: algorithm language-agnostic factorization