Wednesday, March 21, 2018

Smallest Common Multiple - using Euclid's method

I spent some time trying to figure out how I was going to solve the smallest common multiple. There are multiple ways to find this number. You can write down all the multiples and just look, you can use a grid/ladder method, prime factorization, or Euclid's method (the method I selected). If you want to see each method you can go here and see the how to accomplish through the different methods.

I decided to try and use Euclid's method. Math is used to find the greatest common divisor which is then used to find the least common multiple. Euclid's method requires you to perform the same calculation multiple times until you have a remainder of zero. You could do a while statement that looks at the remainder and stops when the remainder is zero. I also looked at a different way to do this, using recursion.

I learned about recursion a while back and figured I would give it a try here. I had a definite stopping point and needed to run the same calculations over until I got a certain number. It took me a few tries at getting the recursion to work (knowing what to put where), but I eventually landed on the below code:

function euclid(high, low) {
if(low === 0) {
return high;
} else {
return euclid(low, high%low);
}
}

I call the function and pass it the first number in an array as the high number and the second number as the low number. It then goes into the function to see that low is not at zero so it calls itself with the low number as high and the remainder of high divided by low (you use modulus to return only the remainder as the new low number. Once the modulus returns a zero, return the high number.

Euclid's method then takes the product of the first original two numbers and divides it by the number returned from our Euclid function. This will give you the smallest common multiple for the two original numbers.


"Laziness may appear attractive, but work gives satisfaction." - Anne Frank

No comments: