What is the fastest way to check if two given numbers are coprime?

こ雲淡風輕ζ 提交于 2019-12-04 10:43:27

问题


One way is to calculate their gcd and check if it is 1.

Is there some faster way?


回答1:


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 their gcd is O(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.




回答2:


if you're running on a machine for which division/remainder is significantly more expensive than shifts, consider binary GCD.



来源:https://stackoverflow.com/questions/1483404/what-is-the-fastest-way-to-check-if-two-given-numbers-are-coprime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!