Skip to content

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 := for i := ; i < len(arr); i++ { n := arr[i] if big.NewInt(int64(i)).ProbablyPrime() { c += n } } return c }
Code language: Go (go)

Option 2:

package solution func Solve(arr []int) int { var sieve = make([]bool, len(arr)) count := 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 }
Code language: Go (go)

Option 3:

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

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 {}, ) 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) }) })
Code language: Go (go)

See also  Floating-point Approximation in Golang
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x