How to Find the Sum of Prime-Indexed Elements in Go


The challenge

You will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices.

The first element of the array is at index ``.

The solution in Golang

Option 1:

package solution 
import "math/big"
func Solve(arr []int) int {
  c := 0
  for i := 0; i < len(arr); i++ {
    n := arr[i]  
    if big.NewInt(int64(i)).ProbablyPrime(0) {
        c += n     
    }
  }
  return c
}

Option 2:

package solution
func Solve(arr []int) int {
  var sieve = make([]bool, len(arr))
  count := 0
  for i := 2; i < len(arr); i++ {
    if !sieve[i] {
      count += arr[i]
      for j := i * i; j < len(sieve); j += i {
        sieve[j] = true
      }
    }
  }
  return count
}

Option 3:

package solution 
func Solve(arr []int) int {
  count := 0
  sum := 0
  for i := 2; i < len(arr); i++{ 
    for c, n := i, 2; c > 0; n++{
      if i % n == 0{
        count++
        c /= n
        n--
      }
    }
    if count < 3 {
      sum += arr[i]
    }
    count = 0
  }
  return sum
}

Test cases to validate our solution

package solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
func dotest(arr []int, exp int) {
    var ans = Solve(arr)
    Expect(ans).To(Equal(exp))
}
var _ = Describe("Example tests", func() {
  It("It should work for basic tests", func() {       
        dotest([]int {}, 0)
        dotest([]int {1,2,3,4},7)  
        dotest([]int {1,2,3,4,5,6}, 13)
        dotest([]int {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},47)       
  })
})