Calculating the Sum of Squares of Integers in Go
January 25, 2023
Problem
Description
- We want you to calculate the sum of squares of given integers, excluding any negatives.- The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow.- Each of the test cases will consist of a line with an integer X (0 < X <= 100), followed by another line consisting of X number of space-separated integers Yn (-100 <= Yn <= 100).- For each test case, calculate the sum of squares of the integers, excluding any negatives, and print the calculated sum in the output.- Note: There should be no output until all the input has been received.- Note 2: Do not put blank lines between test cases solutions.- Note 3: Take input from standard input, and output to standard output.
Rules
You may only use standard library packages. In addition, extra point is awarded if solution does not declare any global variables.
Specific rules for Go solution
- Your source code must be a single file
- Do not use any for and goto statement
package mainfunc main() { ...}
Sample Input
243 -1 1 1459 6 -53 32 16
Sample Output
2061397
Solution
The first solution that comes up to my mind is recursive approach to replace for loop process. In simple step will break down into:
- Get total input number
N
- Get total input number inline with space separator
- Get all number inline input, it should be same with total number defined in step 2
- Repeat step 2 and 3 until
N
- Print calculated the sum of squares of integers excluding negative numbers
Step 1
Entry point application, focus on get first integer only then call recursive read(scanner, numTests, 0, result)
to do the iteration
Step 3
Read input as described in solution step above, line 62 is step 2 and the rest is step 3
Step 4
Calculate positive square sum then store it in array with counter
index.
Step 5
Call read
recursively with counter+1