JOIN
 Select a Forum     Round Tables New Member Discussions News Discussions Algorithm Matches Marathon Matches NASA Tournament Lab TopCoder Cookbook High School Matches Sponsor Discussions Development Forums Design Forums Search | Watch Thread  |  My Post History  |  My Watches  |  User Settings View: Flat  | Threaded  | Tree Previous Thread  |  Next Thread Forums TopCoder Cookbook Algorithm Competitions - Rewriting Phase Using Euclid's Algorithm
 Using Euclid's Algorithm | Reply ProblemYou need to find the greatest common divisor (GCD) or the lowest common multiple (LCM) of two numbers. The GCD of two numbers a and b is the greatest number that divides evenly into both a and b. For example the GCD of 24 and 60 is 12.SolutionBoth of these problems and many others can be solved with Euclid’s algorithm. We will begin by explaining how to obtain GCD and then show that LCM is a simple extension. To compute the GCD naively we could start from the smallest of the two numbers and work our way downwards until we find a number that divides into both of them: ```for (int i=Math.min(a,b); i>=1; i--) if (a%i==0 && b%i==0) return i; ```Although this method is fast enough for most applications, a much faster approach is to use Euclid's algorithm. Euclid's algorithm iterates over the two numbers until a remainder of 0 is found. The algorithm is based on the principle that the GCD of two numbers does not change if the smaller number is subtracted from the larger number. For example, suppose we want to find the GCD of 2336 and 1314. We begin by expressing the larger number (2336) in terms of the smaller number (1314) plus a remainder: ```2336 = 1314 x 1 + 1022 ```We now do the same with 1314 and 1022: ```1314 = 1022 x 1 + 292 ```We continue this process until we reach a remainder of 0: ```1022 = 292 x 3 + 146 292 = 146 x 2 + 0 ```The last non-zero remainder is the GCD. So the GCD of 2336 and 1314 is 146. This algorithm can be easily coded as a recursive function: ```//assume that a and b are positive public long GCD(long a, long b) { if (b==0) return a; return GCD(b,a%b); } ```Using this algorithm we can also find the lowest common multiple (LCM) of two numbers. For example the LCM of 6 and 9 is 18 since 18 is the smallest number that divides both 6 and 9. Notice that 18=(6*9)/3. In general we can express LCM(a,b) as (a*b)/GCD(a,b). To prevent potential overflow we perform division before multiplication in the implementation:```public long LCM(long a, long b) { return b/GCD(a,b)*a; } ```DiscussionEuclid’s algorithm can compute the GCD of large numbers efficiently. In 1844 Gabriel Lamé showed that it never requires more iterations than five times the number of digits h (in base 10) of the smaller number. Since the computational expense of each iteration has order h, the overall complexity grows as h^2.The algorithm has many theoretical and practical applications. It is an important element of the RSA algorithm. It can also be used to solve linear Diophantine equations: equations with integer coefficients of the form ax + by = c. To solve such equations we need a variation of the Euclid's Algorithm, where we record the coefficients floor(a/b) at each step. We can then use these coefficients to find integers c1 and d1 such that |b*c1 - a*d1| = 1. If c does not divide evenly by GCD(a,b) then there are no integer solutions; otherwise there are an infinite number of integer solutions and one of these is x0 = (+/-)c*d1, y0 = (+/-)c*c1. Note that the signs depend on the sign of b*c1 - a*d1, as well as, the signs of a, b and c. Once we have a single solution (x0,y0) then the general solution takes the form x = x0 + b/GCD(a,b)*t, y = y0 - a/GCD(a,b)*t, where t is an arbitrary integer. The following code implements these idea:```// Find solutions to a linear diophantine equation ax+by=c // where a, b and c are integers public void solveDiophantine(long a, long b, long c) { System.out.println("Attempting to solve: "+a+"x + "+b+"y = "+c);   //special case if (a==0 && b==0 && c==0) { System.out.println("x and y can take any value"); return; }   long a1=Math.abs(a); long b1=Math.abs(b); long c1=0, c2=1; long d1=1, d2=0; while(b1>0) { long mult=a1/b1; long temp=c2; c2=c2*mult+c1; c1=temp; temp=d2; d2=d2*mult+d1; d1=temp; temp=b1; b1=a1%b1; a1=temp; }   long gcd=a1; if (gcd==0 || Math.abs(c)%gcd!=0) { System.out.println("There are no integer solutions!"); return; }   long det=c1*d2-c2*d1; long signa=a>0 ? 1: -1; long signb=b>0 ? 1: -1; long x=-d1*c*det*signa/gcd; long y=c1*c*det*signb/gcd; System.out.println("One solution is x="+x+", y="+y); System.out.println("A general solution is x="+x+" + "+b/gcd+"t, y="+y+" - "+a/gcd+"t"); } ```For a more detailed description of the above algorithm, see the following:http://mathworld.wolfram.com/DiophantineEquation.htmlhttp://mathforum.org/library/drmath/view/51595.htmlhttp://www.wikihow.com/Solve-a-Linear-Diophantine-EquationNow let's try solving CommonMultiples (Div I 250 SRM 346). We are asked to count how many numbers between lower and upper inclusive are multiples of all numbers in the set a. We begin by finding the LCM of all numbers in a. It can be shown that LCM of many numbers can be expressed as the LCM of individual pairs, eg., LCM(a, b, c, d) = LCM(a, LCM(b, LCM(c,d))). We find the LCM of all numbers in the first for loop and store it in lcm. We have to be careful, because lcm can overflow an int. To avoid overflow we modify our GCD and LCM functions to return longs. Now, the count of numbers not greater than upper having the required property is upper/lcm (integer division). Similarly, the count of numbers less than lower having the required property is (lower-1)/lcm. Taking the difference of these two results gives us the final answer:```public class CommonMultiples { public int countCommMult(int[] a, int lower, int upper) { long lcm=1; for (int i=0; i0. Thanks to syg96EDIT3: Fixed some bugs in the diophantine code. Should be correct now.
 Subject Author Date Using Euclid's Algorithm dimkadimon Apr 15, 2010 at 8:48 PM EDT Re: Using Euclid's Algorithm dimkadimon Apr 15, 2010 at 9:20 PM EDT Re: Using Euclid's Algorithm Nickolas Jun 28, 2010 at 2:25 AM EDT Re: Using Euclid's Algorithm dimkadimon Jun 29, 2010 at 5:04 AM EDT Re: Using Euclid's Algorithm Nickolas Jun 29, 2010 at 5:14 AM EDT Re: Using Euclid's Algorithm syg96 Oct 23, 2010 at 4:14 AM EDT Re: Using Euclid's Algorithm MauricioC Oct 23, 2010 at 11:48 AM EDT Re: Using Euclid's Algorithm syg96 Oct 23, 2010 at 12:00 PM EDT Re: Using Euclid's Algorithm dimkadimon Oct 26, 2010 at 1:38 AM EDT Re: Using Euclid's Algorithm syg96 Oct 27, 2010 at 7:45 AM EDT Re: Using Euclid's Algorithm dimkadimon Dec 7, 2010 at 9:35 PM EST
 Forums TopCoder Cookbook Algorithm Competitions - Rewriting Phase Using Euclid's Algorithm Previous Thread  |  Next Thread