I'm working on Project Euler questions in order to get used to Go. The question is not about Project Euler, but there is Project Euler specific code in this question that might give away the challenge of a question. "Spoiler Alert" or whatever, but now you know. Here's my file structure:
+ Project Euler
+-+ Go <= GOPATH set here
+-+ src
+-+ util
| +- util.go
|
+- 001.go
+- 002.go
...
+- 023.go
For problem 23, I'm adding a new function SumOfDivisors
to util.go (a file with various methods used by multiple problems):
func GetPrimeFactors(val int) map[int]int {
primes := map[int]int{}
init := val
num := 2
for val > 1 {
if (val % num) == 0 {
if num == init {
return nil
}
_, e := primes[num]
if e {
primes[num]++
} else {
primes[num] = 1
}
val /= num
} else {
num++
}
}
return primes
}
func SumOfDivisors(val int) int {
primes := GetPrimeFactors(val)
if primes == nil {
if val == 0 {
return 0
} else {
return 1
}
}
total := 1
for k, v := range primes {
if v > 1 {
n := int((math.Pow(float64(k), float64(v+1)) - 1) / float64(k-1))
total *= n
} else {
n := k + 1
total *= n
}
}
return total - val
}
In order to test this method, I wrote this basic Go inside 023.go:
package main
import (
"fmt"
"util"
)
func main() {
fmt.Println(util.SumOfDivisors(12))
}
I have my GOPATH
set to /Project Euler/Go
and it builds and runs seemingly fine when I call go run 023.go
. "Seemingly fine" meaning there are no errors, warnings, no output other than my code.
What is printing to the screen is 1
when it should be 16
. I don't think it's a logic issue because when I copy the function from my util.go into 023.go (and fix the call to GetPrimeFactors to be util.GetPrimeFactors) then the function runs just fine and prints 16 just like it should. I've tried adding fmt.Println("TEST")
to util.SumOfDivisors
but it won't print those statements out and I don't get errors or anything else. If I change the name of the function in util.go
to anything else, even if the main function is 023.go
doesn't change, it still builds and runs outputting 1
. It's really behaving weird.
Other functions in my util.go file seem to be called just fine.
I'm running Go 1.4.2. What might be causing this kind of behavior? The function works properly locally but not when moved to an external file that's imported and why can't that external file print anything to screen? All this while building just fine.