[Golang] Smallest Multiple - Problem 5 - Project Euler


Go solution to smallest multiple - Problem 5 - Project Euler. [1]

Problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Solution:

LCM(1, 2, 3, ..., 20) = 18044195

Run Code on Go Playground

package main

import (
      "fmt"
)

// greatest common divisor (GCD) via Euclidean algorithm
func GCD(a, b int) int {
      for b != 0 {
              t := b
              b = a % b
              a = t
      }
      return a
}

// find Least Common Multiple (LCM) via GCD
func LCM(a, b int) int {
      return a * b / GCD(a, b)
}

func main() {
      result := 1
      for j := 2; j <= 20; j++ {
              result = LCM(result, j)
      }
      fmt.Println(result)
}

Tested on Go Playground.


References:

[1]Smallest multiple - Problem 5 - Project Euler
[2][Golang] Greatest Common Divisor via Euclidean Algorithm
[3]LCM Calculator - Least Common Multiple