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

120
Views
Calculating sum of fractions in a loop

Implement a function fractionSum(n) that calculates and returns the sum of the following sequence: 1/n + 1/(n−1) + 1/(n−2) + ⋅⋅⋅ + 1/2 + 1

For example, fractionSum(5) calculates the following sum: 1/5+1/4+1/3+1/2+1 And then returns 2.283333333333333

I haven't even started writing function just yet since I'm still stuck at trying to figure out the right loop expression. This is what I've done so far:

        var sum =0;
        var fraction = 1;
        
        var number = parseInt(prompt("Enter an integer: ", "5"));
       
        for ( var counter = 0; counter <= number; counter++) {
            fraction /= (number - counter); // do I need to declare parseFloat here for decimal# ?
            sum += fraction;
        }     
        document.write("The total value is " + sum);

The number doesn't match up at all from the example. I'm not sure what the problem is here.

I'm pretty confused right now. I know this is basic problem but I has tried multiple codes and it still didn't come out right.

Thank you so much

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

0

You're reusing the fraction from the previous iteration and dividing it by the next value. You need a new fraction instead:

fraction = 1 / (number - counter);

Also, you need the strict counter < number condition in the loop to avoid division by zero.

about 4 years ago · Juan Pablo Isaza Report

0

In the loop, counter must be less than number else at the end there will be divison by 0, the result will be infinity. Try this

let sum = 0;
let i = 0;
let num = parseInt(prompt("Enter an integer: ", "5"));
for(i; i < num; i++ ){
  frac = 1 / ( num - i);
  sum+= frac;
}
about 4 years ago · Juan Pablo Isaza Report

0

I figured it out. This is what I got:

<script>
    function fractionSum(number) {
        var sum =0;
        for (var counter= 0 ; counter < number; counter++) {   
            sum += 1/(number - counter);
        }  
        return sum;
    }

    var number = parseInt(prompt("Enter the value of n: ", "5"));
    sum = fractionSum(number);
    document.write("The fraction sum of order " + number + " is " + sum);
</script>

Thank you guys, it was very helpful

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!