Software Engineering

How one can Calculate Dominant Primes in Golang

How one can Calculate Dominant Primes in Golang
Written by admin


The problem

The prime quantity sequence begins with: 2,3,5,7,11,13,17,19.... Discover that 2 is in place one.

3 occupies place two, which is a prime-numbered place. Equally, 511 and 17 additionally occupy prime-numbered positions. We will name primes similar to 3,5,11,17 dominant primes as a result of they occupy prime-numbered positions within the prime quantity sequence. Let’s name this listA.

As you may see from listA, for the prime vary vary(0,10), there are solely two dominant primes (3 and 5) and the sum of those primes is: 3 + 5 = 8.

Equally, as proven in listA, within the vary (6,20), the dominant primes on this vary are 11 and 17, with a sum of 28.

Given a vary (a,b), what’s the sum of dominant primes inside that vary? Be aware that a <= vary <= b and b won’t exceed 500000.

The answer in Golang

Choice 1:

package deal answer
func Resolve(a, b int) int {
  sum := 0
  sv := make([]bool, b+1)
  pos := 1
  if a <= 3 && b >= 3 {
    sum += 3
  }
  for i := 3; i <= b; i += 2 {
    if sv[i] == false {
      pos++
      if i >= a && pospercent2 == 1 && sv[pos] == false {
        sum += i
      }
      for j := i + i; j <= b; j += i {
        sv[j] = true
      }
    }
  }
  return sum
}

Choice 2:

package deal answer
func Resolve(a, b int) (sum int) {
  primes := make([]int, 0, 5000)
  primes = append(primes, 2, 3, 5, 7)
  prime := func(n int) int { 
    for n > len(primes) {
      subsequent := primes[len(primes) - 1] + 1
      for i := 0; primes[i]*primes[i] <= subsequent; i++ {
        if nextpercentprimes[i] == 0 { subsequent += 1 ; i = -1 }
      }
      primes = append(primes, subsequent)
    }
    return primes[n-1]
  }
  for i := 1 ;; i++ {
    dominantPrime := prime(prime(i))
    if dominantPrime > b { break }
    if dominantPrime < a { proceed }
    sum += dominantPrime
  }
  return
}

Choice 3:

package deal answer
func isPrime(n int) bool {
  for i := 2; i*i < n+i; i++ {
    if npercenti == 0 {
      return false
    }
  }
  return n > 1
}
func Resolve(a, b int) int {
  c, pos := 0, 0
  for i := 0; i <= b; i++ {
    if isPrime(i) {
      pos++
      if i >= a && isPrime(pos) {
        c += i
      }
    }
  }
  return c
}

Check instances to validate our answer

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
func dotest(s, g, exp int) {
    var ans = Resolve(s,g)
    Anticipate(ans).To(Equal(exp))
}
var _ = Describe("Instance exams", func() {
  It("It ought to work for fundamental exams", func() {       
        dotest(0,10, 8)
        dotest(2,200, 1080)    
        dotest(1000,100000,52114889)
        dotest(4000,500000,972664400)         
  })
})

About the author

admin

Leave a Comment