Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this considered a recursive algorithm?

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!!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading