views:

236

answers:

2

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

Is there some faster way?

+10  A: 

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.

Jason
I'd like to comment that it's a bit coarse to measure complexity of arithmetic algorithms without taking costs of arithmetic operations into account.
Pavel Shved
The worstcase # of steps is O(log n) as well, when two numbers are successive entries in the Fibonacci sequence.
Jason S
@Pavel Shved: I did take the cost into consideration. cf. the sentence "The average computation time required for each step is quadratic in the number of digits."
Jason
@everyone thanks.
Lazer
+5  A: 

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

Jason S
Thanks, interesting read
jcinacio
yeah, a very good article there.
Lazer