본문 바로가기
알고리즘/Codewars

[Codewars] Sum of the first nth term of Series (7 kyu) / JavaScript

by fluss 2023. 1. 31.

https://www.codewars.com/kata/555eded1ad94b00403000071

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Task:

Your task is to write a function which returns the sum of following series upto nth term(parameter).

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

 

Rules:

  • You need to round the answer to 2 decimal places and return it as String.
  • If the given value is 0 then it should return 0.00
  • You will only be given Natural Numbers as arguments.

 

Examples:(Input --> Output)

1 --> 1 --> "1.00"
2 --> 1 + 1/4 --> "1.25"
5 --> 1 + 1/4 + 1/7 + 1/10 + 1/13 --> "1.57"

 

코드

function SeriesSum(n)
{
  let sum = 0;
  let num = 1;
  for(let i = 0; i < n; i++){
    sum += 1 / num;
    num += 3;
  }
  return sum.toFixed(2);
}

댓글