k.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package kata
  2. import (
  3. "fmt"
  4. "math/big"
  5. )
  6. // Documented as exact up to 2^64.
  7. func isPrime(n int) bool {
  8. return big.NewInt(int64(n)).ProbablyPrime(1)
  9. }
  10. /*
  11. Gap returns the first pair of two prime numbers spaced with the specified gap,
  12. if one exists. Otherwise, it returns nil.
  13. - gap >= 2 is the gap we are looking for
  14. - start > 2 is the start of the search, inclusive
  15. - end >= start is the end of the search, inclusive
  16. */
  17. func Gap(gap, start, end int) []int {
  18. var res []int
  19. fmt.Printf("%d %d-%d\n", gap, start, end)
  20. // Handle degenerate cases first.
  21. if gap%2 == 1 {
  22. return res
  23. }
  24. if start%2 == 0 {
  25. start++
  26. }
  27. if start >= end {
  28. return res
  29. }
  30. var low, high int
  31. External:
  32. for low = start; low <= end-gap; low += 2 {
  33. high = low + gap
  34. if !isPrime(low) || !isPrime(high) {
  35. continue
  36. }
  37. // We have a prime pair. Is it a gap ?
  38. for mid := low + 2; mid < high; mid++ {
  39. // If there is a smaller pair, it's not a gap.
  40. if isPrime(mid) {
  41. continue External
  42. }
  43. }
  44. // It's a gap!
  45. return []int{low, high}
  46. }
  47. return nil
  48. }