Your current solution is incorrect, as mentioned in the comments.
One way to solve this is to realize that the LCM of these numbers is just the product of all the "greatest" degrees of various prime numbers less than or equal to n . That is, find each prime p less than or equal to n , then find the greatest degree of each of these primes, such that it is even less than or equal to n , and multiply them together. For a given p indicated power can be expressed in pseudo-code as:
p ** math.Floor(math.Log(n) / math.Log(p))
Here's the implementation in Golang, which returns immediately:
http://play.golang.org/p/8s4eE_CQ9Y
$ time go run lcm.go 5793339670287642968692270879166240098634860297998518825393138351148979300145773182308832598 <several lines later> 800000 real 0m0.225s user 0m0.173s sys 0m0.044s
For completeness, here is the full code from this playground:
package main import ( "fmt" "math" "math/big" ) func main() { n := 10001 primes := make([]int, 1, n) primes[0] = 2 SIEVE: for i := 3; i <= n; i++ { for _, p := range primes { if i%p == 0 { continue SIEVE } } primes = append(primes, i) } logN := math.Log(float64(n)) lcm := big.NewInt(1) for _, p := range primes { floatP := float64(p) e := math.Floor(logN / math.Log(floatP)) lcm.Mul(lcm, big.NewInt(int64(math.Pow(floatP, e)))) } fmt.Println(lcm) }
source share