Tuesday, January 31, 2023
HomeSoftware EngineeringTips on how to Calculate Dominant Primes in Golang

# Tips on how to Calculate Dominant Primes in Golang

## 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, `5``11` 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’ll be able to 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? Observe that `a <= vary <= b` and `b` won’t exceed `500000`.

Possibility 1:

``````package deal resolution
func Remedy(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
}
``````

Possibility 2:

``````package deal resolution
func Remedy(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
}
``````

Possibility 3:

``````package deal resolution
func isPrime(n int) bool {
for i := 2; i*i < n+i; i++ {
if npercenti == 0 {
return false
}
}
return n > 1
}
func Remedy(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
}
``````

## Take a look at circumstances to validate our resolution#

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