Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.12 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. var primes = []int{2, 3, 5, 7}
  6. var primesSquared = []int{4, 9, 25, 49}
  7.  
  8. func main() {
  9.     start, maxLength := 9, 100000
  10.  
  11.     for i := start; len(primes) < maxLength; i += 2 {
  12.         if isPrime(i) {
  13.             primes = append(primes, i)
  14.             primesSquared = append(primesSquared, i*i)
  15.         }
  16.     }
  17.  
  18.     for _, i := range primes {
  19.         fmt.Println(i)
  20.     }
  21. }
  22.  
  23. // possibleFactorsIndex returns an index in the primeSquared where
  24. // primeSquared[index] <= n
  25. // An index of -1 is special, meaning we actually found n in primeSquared
  26. //
  27. func possibleFactorsIndex(n int) int {
  28.     // fmt.Println("looking at", n)
  29.     low, high, mid := 0, len(primes), 0
  30.     for high != low+1 {
  31.         mid = (low + high) / 2
  32.         // fmt.Println("low =", low, ", high =", high, ", mid =", mid)
  33.         if primesSquared[mid] > n {
  34.             high = mid
  35.             continue
  36.         }
  37.         if primesSquared[mid] < n {
  38.             low = mid
  39.             continue
  40.         }
  41.         return -1
  42.     }
  43.     return high
  44. }
  45.  
  46. func isPrime(n int) bool {
  47.     topIndex := possibleFactorsIndex(n)
  48.     if topIndex == -1 {
  49.         return false
  50.     }
  51.     for i := 1; i < topIndex; i++ {
  52.         if n%primes[i] == 0 {
  53.             return false
  54.         }
  55.     }
  56.     return true
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement