Permalink
Browse files

Euler #21

This is a prime candidate for parallelization but it's fast enough as it is.
  • Loading branch information...
1 parent 90d1f58 commit f70fce61e2d5894fc82c67d7fa04a5055105f365 Evan Farrer committed Jan 15, 2012
Showing with 74 additions and 0 deletions.
  1. +11 −0 Euler021/Makefile
  2. +63 −0 Euler021/main.go
View
@@ -0,0 +1,11 @@
+results: main
+ ./main > results
+
+main: main.6
+ 6l -o main *.6
+
+main.6: main.go
+ gofmt -w=true *.go && 6g *.go
+
+clean:
+ rm main *.6 results
View
@@ -0,0 +1,63 @@
+package main
+
+import "fmt"
+import "runtime"
+
+func sum(nums []int) int {
+ total := 0
+ for i := 0; i != len(nums); i++ {
+ total += nums[i]
+ }
+ return total
+}
+
+func properDivisors(num int) []int {
+ divisors := make([]int, 0, 10)
+ for i := 1; i <= (num / 2); i++ {
+ if 0 == (num % i) {
+ divisors = append(divisors, i)
+ }
+ }
+
+ return divisors
+}
+
+func getAmicablePair(num int) (int, bool) {
+ pair := sum(properDivisors(num))
+
+ // Amicable pair can't be itself
+ if pair == num {
+ return 0, false
+ }
+
+ orig := sum(properDivisors(pair))
+
+ // If it doesn't transform back to us then it's not amicable
+ if orig != num {
+ return 0, false
+ }
+
+ // Yea we're amicable
+ return pair, true
+}
+
+func main() {
+ runtime.GOMAXPROCS(1)
+
+ amicablePairs := map[int]bool{}
+
+ for i := 1; i < 10000; i++ {
+ pair, amm := getAmicablePair(i)
+ if amm {
+ amicablePairs[i] = true
+ amicablePairs[pair] = true
+ }
+ }
+
+ total := 0
+ for key, _ := range amicablePairs {
+ total += key
+ }
+
+ fmt.Printf("%v", total)
+}

0 comments on commit f70fce6

Please sign in to comment.