英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论