Browse Source

K5 Gap in primes

Frederic G. MARAND 4 years ago
parent
commit
138b84e16f

+ 11 - 0
go/.idea/runConfigurations/k5_gap_in_primes.xml

@@ -0,0 +1,11 @@
+<component name="ProjectRunConfigurationManager">
+  <configuration default="false" name="k5 gap in primes" type="GoTestRunConfiguration" factoryName="Go Test">
+    <module name="codewars" />
+    <working_directory value="$PROJECT_DIR$/" />
+    <go_parameters value="-i" />
+    <framework value="gotest" />
+    <kind value="PACKAGE" />
+    <package value="code.osinet.fr/fgm/codewars/kyu5/gap_in_primes" />
+    <method v="2" />
+  </configuration>
+</component>

+ 13 - 0
go/kyu5/gap_in_primes/gap_in_primes_suite_test.go

@@ -0,0 +1,13 @@
+package kata_test
+
+import (
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+func TestGapInPrimes(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "GapInPrimes Suite")
+}

+ 52 - 0
go/kyu5/gap_in_primes/k.go

@@ -0,0 +1,52 @@
+package kata
+
+import (
+	"fmt"
+	"math/big"
+)
+
+// Documented as exact up to 2^64.
+func isPrime(n int) bool {
+	return big.NewInt(int64(n)).ProbablyPrime(1)
+}
+
+/*
+Gap returns the first pair of two prime numbers spaced with the specified gap,
+if one exists. Otherwise, it returns nil.
+
+ - gap >= 2 is the gap we are looking for
+ - start > 2 is the start of the search, inclusive
+ - end >= start is the end of the search, inclusive
+*/
+func Gap(gap, start, end int) []int {
+	var res []int
+	fmt.Printf("%d %d-%d\n", gap, start, end)
+	// Handle degenerate cases first.
+	if gap%2 == 1 {
+		return res
+	}
+	if start%2 == 0 {
+		start++
+	}
+	if start >= end {
+		return res
+	}
+	var low, high int
+External:
+	for low = start; low <= end-gap; low += 2 {
+		high = low + gap
+		if !isPrime(low) || !isPrime(high) {
+			continue
+		}
+		// We have a prime pair. Is it a gap ?
+		for mid := low + 2; mid < high; mid++ {
+			// If there is a smaller pair, it's not a gap.
+			if isPrime(mid) {
+				continue External
+			}
+		}
+		// It's a gap!
+		return []int{low, high}
+	}
+	return nil
+}

+ 29 - 0
go/kyu5/gap_in_primes/k_test.go

@@ -0,0 +1,29 @@
+package kata_test
+
+import (
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+
+	. "code.osinet.fr/fgm/codewars/kyu5/gap_in_primes"
+)
+
+func dotest(k, start, nd int, exp []int) {
+	var ans = Gap(k, start, nd)
+	Expect(ans).To(Equal(exp))
+}
+
+var _ = Describe("Test Example", func() {
+
+	It("should handle basic cases", func() {
+		dotest(2, 100, 110, []int{101, 103})
+		dotest(4, 100, 110, []int{103, 107})
+		dotest(6, 100, 110, nil)
+		dotest(8, 300, 400, []int{359, 367})
+		dotest(10, 300, 400, []int{337, 347})
+		dotest(4, 30000, 100000, []int{30109, 30113})
+		dotest(6, 30000, 100000, []int{30091, 30097})
+		dotest(8, 30000, 100000, []int{30161, 30169})
+		dotest(11, 30000, 100000, nil)
+		dotest(2, 10000000, 11000000, []int{10000139, 10000141})
+	})
+})