PageRenderTime 23ms CodeModel.GetById 16ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/prime_factor_sum.go

https://code.google.com/p/go-prime-factor-sum/
Go | 40 lines | 37 code | 3 blank | 0 comment | 9 complexity | c7d0c7d0a43f721ca7c8576ef046a236 MD5 | raw file
 1package main
 2
 3import (
 4  "flag"
 5  "fmt"
 6  "os"
 7)
 8
 9func PrimeFactorSum(n int) int {
10  notPrime := make([]bool, n + 1)
11  rem := n
12  sum := 0
13  nextPrime := 2
14  for {
15    if rem % nextPrime == 0 {
16      sum += nextPrime
17      for {
18        rem /= nextPrime
19        if rem % nextPrime != 0 {
20          break
21        }
22      }
23    }
24    if rem <= 1 {
25      break
26    }
27    last := n / nextPrime
28    for i := 2; i <= last; i++ {
29      notPrime[i * nextPrime] = true
30    }
31    for nextPrime = nextPrime + 1; notPrime[nextPrime]; nextPrime++ { }
32  }
33  return sum
34}
35
36func main() {
37  n := flag.Int("n", 1, "Sum up unique prime factors of n")
38  flag.Parse()
39  fmt.Fprintf(os.Stdout, "%d\n", PrimeFactorSum(*n))
40}