Skip to content

Instantly share code, notes, and snippets.

@anuragdhingra
Last active May 18, 2020 10:32
Show Gist options
  • Save anuragdhingra/6ba269d7bbb85362615408d16226cee0 to your computer and use it in GitHub Desktop.
Save anuragdhingra/6ba269d7bbb85362615408d16226cee0 to your computer and use it in GitHub Desktop.
Sum of squares without using a for loop in go.
package main
import "fmt"
// Global vars
var arr []int
var sos int
func check(err error) {
if err != nil {
panic(err)
}
}
func recursiveSOS(t int) {
if t == 0 {
return
}
// Read no of elements in array
var n int
_, err := fmt.Scanf("%d", &n)
check(err)
// Read the array elements
readArray(n)
// Print sum of square (SOS)
printSOS(n)
// Reset the global vars
arr = arr[:0]
sos = 0
// Iterate to next test case
recursiveSOS(t-1)
}
func readArray(size int) {
if size == 0 {
return
}
var i int
_, err := fmt.Scanf("%d", &i)
check(err)
arr = append(arr, i)
readArray(size - 1)
}
func printSOS(size int) {
if size == 0 {
fmt.Println(sos)
return
}
i := size - 1
if arr[i] > 0 {
sos += arr[i] * arr[i]
}
printSOS(size-1)
}
func main() {
var t int
_, err := fmt.Scanf("%d", &t)
check(err)
recursiveSOS(t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment