Skip to content

Instantly share code, notes, and snippets.

@knsmr
Created August 24, 2014 09:43
Show Gist options
  • Save knsmr/098ded20ec89e81723fe to your computer and use it in GitHub Desktop.
Save knsmr/098ded20ec89e81723fe to your computer and use it in GitHub Desktop.
package main
// Euler Project #50: http://projecteuler.net/problem=50
import (
"fmt"
"math"
"runtime"
)
func main() {
fmt.Printf("Number of CPUs: %d\n", runtime.NumCPU())
runtime.GOMAXPROCS(runtime.NumCPU())
primes := getPrimes(1000000)
fmt.Println("... ", primes[len(primes) - 10:])
l := len(primes) - 1
ch := make(chan []int)
ch2 := make(chan int)
for i := l; i >= 0; i-- {
go checkPrime(i, l, primes , ch, ch2)
}
var max int
var num int = 0
var a, answer []int
Loop:
for {
select {
case <- ch2: {
num++
if num >= l {
break Loop
}
}
case a = <- ch: {
if a[0] > max {
answer = a
max = a[0]
}
}
}
}
fmt.Println(answer)
}
func checkPrime(i, l int, primes []int, ch chan []int, ch2 chan int) {
var sum int = 0
for j := 0; j <= l; j++ {
sum = 0
for k := j; k <= l; k++ {
sum += primes[k]
if sum > primes[i] {
break
}
if sum == primes[i] {
ch <- []int{k -j, sum}
}
}
}
ch2 <- 1
}
func getPrimes(n int) []int {
var primeList = []int{2}
var isPrime bool = true
var num int = 3
var sqrtNum int = 0
for num < n {
sqrtNum = int(math.Sqrt(float64(num)))
for i := 0; i < len(primeList); i++ {
if num % primeList[i] == 0 {
isPrime = false
}
if primeList[i] > sqrtNum {
i = len(primeList)
}
}
if isPrime {
primeList = append(primeList, num)
} else {
isPrime = true
}
num = num + 2
}
return primeList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment