Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Recursive SUM function javascript

I have been given the function below in pseudocode and I am trying to translate it to JS, but I keep getting an infinity loop.


Update

Thanks zord, mid fixed the recursion issue. Now I get the wrong sum, any suggestions?

What am I doing wrong?

function SUM(arr, left, right){
  
    if(left > right){ 
        return 0 
    }
    else if(left == right){
      return arr[left]
    }

    mid = Math.floor((left + right) / 2);

    lsum = SUM(arr,left,mid);
    rsum = SUM(arr,mid+1,right); 

    return lsum + rsum

}

arr = [1,2,3,4,5]
left = 0;
right = arr.length - 1;


console.log(SUM(arr, left, right));

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

mid should be halfway between left and right:

mid = Math.floor((left + right) / 2);

Also, you need to make your variables block scoped as VLAZ mentioned. Otherwise they will be global, and overwritten by different runs of the function.

const mid = Math.floor((left + right) / 2);

const lsum = SUM(arr, left, mid);
const rsum = SUM(arr, mid + 1, right); 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!