You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go语言中不使用for语句实现正整数平方和计算?

How to Calculate Sum of Squares (Excluding Negatives) in Go Without Using for Statements

Hey there! I see you've already got a working implementation using for loops, but since the requirement bans for statements, recursion is our perfect alternative here—it’s a clean way to replace iterative logic without relying on loops, and we can stick strictly to Go’s standard library.

The Approach

We’ll use recursive functions to handle two layers of iteration:

  1. A recursive function to process each of the N test cases one by one.
  2. Another recursive function to read X numbers per test case, calculate the sum of squares for non-negative values, and return the total.

Compliant Go Implementation

package main

import "fmt"

// processTestCases handles N test cases recursively
func processTestCases(n int) {
	if n <= 0 {
		return
	}

	var x int
	fmt.Scan(&x)
	sum := calculateSum(x)
	fmt.Println(sum)

	processTestCases(n - 1)
}

// calculateSum reads x numbers and returns sum of squares of positive values
func calculateSum(x int) int {
	if x <= 0 {
		return 0
	}

	var y int
	fmt.Scan(&y)

	current := 0
	// Match your original logic: only include positive numbers (exclude negatives and zero)
	if y > 0 {
		current = y * y
	}

	return current + calculateSum(x - 1)
}

func main() {
	var n int
	fmt.Scan(&n)
	processTestCases(n)
}

Verify with Your Example Input

Input:

2
4
3 -1 1 14
5
9 6 -53 32 16

Output:

206
1397

This matches exactly the expected result from your original code!

Key Changes from Your Original Code

  • Replaced the outer for loop (processing N test cases) with processTestCases: we keep calling the function with n-1 until we’ve handled all test cases.
  • Replaced the inner for loop (reading X numbers) with calculateSum: each call reads one number, adds its square if it’s positive, then recurses with x-1 until all X numbers are processed.
  • We’re still only using the fmt standard library, so we meet the "仅用标准库" requirement perfectly.

Quick Edge Case Note

If you need to include zero in the sum (since the problem mentions "非负整数"), just adjust the condition in calculateSum to y >= 0—the code is easy to tweak here to match exact requirements.

内容的提问来源于stack exchange,提问作者w0lf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:08:54