Skip to content

Instantly share code, notes, and snippets.

@Cartmanishere
Created May 16, 2019 02:46
Show Gist options
  • Save Cartmanishere/ff01432fe9774c391f4cd54a434836dc to your computer and use it in GitHub Desktop.
Save Cartmanishere/ff01432fe9774c391f4cd54a434836dc to your computer and use it in GitHub Desktop.
Calculate the sum of squares of positive numbers in golang without using for statement
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
n, _ := reader.ReadString('\n')
n = strings.TrimRight(n, "\r\n")
test_cases, err := strconv.Atoi(n)
if err != nil {
fmt.Println(err)
}
process_test_case(test_cases, reader)
}
func process_test_case(test_cases int, reader *bufio.Reader) {
if test_cases != 0 {
_, _ = reader.ReadString('\n')
input, _:= reader.ReadString('\n')
input = strings.TrimRight(input, "\r\n")
arr := strings.Split(input, " ")
ans := process_array(arr, 0)
fmt.Println(ans)
test_cases -= 1
process_test_case(test_cases, reader)
}
}
func process_array(arr []string, result int) int {
num, _ := strconv.Atoi(arr[0])
if len(arr) > 1 {
next := arr[1:]
if num < 0 {
num = 0
}
result = num * num + process_array(next, result)
return result
} else {
if num >= 0 {
return num * num
}
return 0
}
}
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment