检查两个给定数字是否互质的最快方法是什么?
一种方法是计算它们的gcd并检查它是否为1。
有没有更快的方法?
One way is to calculate their gcd and check if it is 1.
Is there some faster way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
欧几里得算法(计算
gcd
)非常快。当从[1, n]
中均匀随机抽取两个数字时,计算其gcd
的平均步数为O(log n)
。每个步骤所需的平均计算时间是位数的二次方。有一些替代方案的性能稍好(即,每个步骤都是位数的次二次方),但它们仅对非常大的整数有效。例如,请参阅关于 Schönhage 算法和次二次整数 gcd 计算。
The Euclidean algorithm (computes
gcd
) is very fast. When two numbers are drawn uniformly at random from[1, n]
, the average number of steps to compute theirgcd
isO(log n)
. The average computation time required for each step is quadratic in the number of digits.There are alternatives that perform somewhat better (i.e., each step is subquadratic in the number of digits), but they are only effective on very large integers. See, for example, On Schönhage's algorithm and subquadratic integer gcd computation.
如果您运行的机器上的除法/余数比班次贵得多,请考虑二进制 GCD。
if you're running on a machine for which division/remainder is significantly more expensive than shifts, consider binary GCD.