这被视为递归算法吗?

huangapple go评论158阅读模式
英文:

Is this considered a recursive algorithm?

问题

该算法的目标是使用递归算法找到具有n个数字的序列A的倒数之和。

findSum(A, n){
	Sum = 0
	if (n == 1) {
		return 1/A[0]
	}
	else {
		return A[n-1]
		Sum += 1/A[n-1]
	}
	return Sum
}

有人可以帮我吗?非常感谢!!!

英文:

The aim of the algorithm is to find the sum of the reciprocal of Sequence A with n numbers, using recursive algorithm.

findSum(A,n){
	Sum = 0
	if (n == 1) {
		return 1/A[0]
		}
	else {
		return A[n-1]
		Sum += 1/A[n-1]
	}
	return Sum
}

Can someone help me? Thanks a lot!!!

答案1

得分: 0

如其他人指出的,你从未在函数内部调用它自己,所以不,它不是递归的。

有多种方法可以解决这个问题,但你应该考虑你要对什么以及在哪里进行求和。你在函数内部声明了总和,但你只取了最后一项的倒数。

想想你将如何处理倒数第二个数的下一次迭代。你可以将总和的范围限定在函数外部,将其作为参数传递,或者直接在返回语句中进行求和。

findSum(A, n){       
  return 1/A[n-1] + findSum(A, n-1)
}
英文:

As other pointed out, you're never calling the function within itself, so no, it's not recursive.

There are multiple ways to go about this but you should think about what and where exactly are you summing up. You declared the sum within the function but you only take the reciprocal of the last item.

Think how would you go about the next iteration for the number before the last one. You can scope the sum outside the function, pass it as a parameter, or make the sum right in the return statement.

findSum(A, n){       
  return 1/A[n-1] + findSum(A, n-1)
}

huangapple
  • 本文由 发表于 2023年7月27日 22:24:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定