4

Given $a_1,...,a_n$

$gcd(a_1,...,a_n) = b$

I need to find $i$, so if i apply euclids algorithm to $(a_1,a_i)$, i end with $(0,b)$ or $(b,0)$.

poet
  • 41
  • 5
    There might not be an $i$ such that $\gcd(a_1, a_i) = b$ (like in the list $30, 20, 45, 10, 15$, where $b = 5$ but $\gcd(a_1, a_i)$ is either $10$ or $15$). What would you do then? – Arthur Feb 20 '15 at 06:54
  • How about this: to calculate the first $gcd(a_1,...,a_n) = b$, i calculate $(gcd(gcd(a_1,a_2),a_3)...)$. I remember every intermediate result and at the end i look which of these intermediate results is equal to b and i have found the one im looking for? – poet Feb 20 '15 at 08:00
  • @Arthur do you think that works, or does this fail? In each intermediate result the gcd is falling. so i take a look at the element the first time it hit the final minimum – poet Feb 20 '15 at 08:55
  • That would do it. Doing successive gcd's, you get the total gcd in the end. It's a good exercise to prove $\gcd(a,b,c) = \gcd(\gcd(a,b),c)$ just to convince yourself that it works in the simplest case. – Arthur Feb 20 '15 at 14:06
  • @poet yes, gcd is associative so you can always reduce such n-ary gcds to binary gcds. – Bill Dubuque Feb 20 '15 at 15:19

2 Answers2

1

Say we have the numbers $$ 30, 20, 15, 10, 45 $$ then the greatest common divisor of all those numbers is $5$, but if you take $\gcd(a_1, a_i)$ for $2\leq i \leq 5$, you get the list $$ 10, 15, 10, 15 $$ and none of those are equal to $5$. To get the correct answer, you have to repeat the process with the new list until only one number remains (i.e. all numbers on the list, possibly one, possibly many, are equal). To get to the answer faster, though, it might be a good idea to start with not the first number in the list, but the smallest. Had we used $a_4 = 10$ in all our checks instead of $a_1 = 30$, we would've gotten $$ 10, 10, 5, 5 $$ which is a better intermediate point.

Arthur
  • 204,511
0

You can always reduce the set one number at a time:

$$\gcd(a_1,a_2,\ldots,a_{n-1},a_n) = \gcd(a_1,a_2,\ldots,\gcd(a_{n-1},a_n)).$$

There is also a well-known algorithm that does three numbers at a time. Label the numbers $x,y,z$ so that $z$ is the smallest. To find $\gcd(x,y,z)$, divide each of $x$ and $y$ by $z$ with remainder:

$$\begin{eqnarray} x &=& q_1z + r_1,\ & 0 \leq r_1 < z,\\ y &=& q_2z + r_2,\ & 0 \leq r_2 < z. \end{eqnarray}$$

If the remainders are both zero, $z = gcd(x,y,z)$. Otherwise, set $x',y',z'$ to $r_1, r_2, z,$ but assign them in order so that $z'$ is smaller than $x'$ or $y'$. Then find $\gcd(x', y', z').$

This can be extended to larger lists of numbers. At each step, always choose the smallest number as the divisor of all the others.

David K
  • 108,155