Wednesday, February 21, 2024
HomeSoftware EngineeringTips on how to Discover the Sum of Prime-Listed Components in Go

Tips on how to Discover the Sum of Prime-Listed Components in Go


The problem

You may be given an integer array and your job is to return the sum of components occupying prime-numbered indices.

The primary aspect of the array is at index “.

The answer in Golang

Choice 1:

bundle answer 
import "math/large"
func Clear up(arr []int) int {
  c := 0
  for i := 0; i < len(arr); i++ {
    n := arr[i]  
    if large.NewInt(int64(i)).ProbablyPrime(0) {
        c += n     
    }
  }
  return c
}

Choice 2:

bundle answer
func Clear up(arr []int) int {
  var sieve = make([]bool, len(arr))
  rely := 0
  for i := 2; i < len(arr); i++ {
    if !sieve[i] {
      rely += arr[i]
      for j := i * i; j < len(sieve); j += i {
        sieve[j] = true
      }
    }
  }
  return rely
}

Choice 3:

bundle answer 
func Clear up(arr []int) int {
  rely := 0
  sum := 0
  for i := 2; i < len(arr); i++{ 
    for c, n := i, 2; c > 0; n++{
      if i % n == 0{
        rely++
        c /= n
        n--
      }
    }
    if rely < 3 {
      sum += arr[i]
    }
    rely = 0
  }
  return sum
}

Take a look at circumstances to validate our answer

bundle solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
func dotest(arr []int, exp int) {
    var ans = Clear up(arr)
    Anticipate(ans).To(Equal(exp))
}
var _ = Describe("Instance checks", func() {
  It("It ought to work for fundamental checks", 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)       
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments