Source

euler / go / src / euler / primes.go

package primes

func integers() chan uint64 {
	out := make(chan uint64)

	go func() {
		var i uint64 = 2
		for {
			out <- i
			i++
		}
	}()

	return out
}

func filter(prime uint64, in chan uint64) chan uint64 {
	out := make(chan uint64)

	go func() {
		for i := range in {
			if (i % prime) != 0 {
				out <- i
			}
		}
	}()

	return out
}

func Primes() chan uint64 {
	out := make(chan uint64)
	in := integers()
	go func() {
		for {
			i := <-in
			out <- i
			in = filter(i, in)
		}
	}()

	return out
}

var primes []uint64 = nil
var pgen = Primes()

func fillPrimes(n uint64) {
	for {
		if len(primes) > 0 && primes[len(primes)-1] > n {
			return
		}
		p := <-pgen
		primes = append(primes, p)
	}
}

func search(needle uint64, haystack []uint64) bool {
	for _, v := range haystack {
		if needle == v {
			return true
		}
	}

	return false
}

func IsPrime(n uint64) bool {
	fillPrimes(n)
	return search(n, primes)
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.