Algorithm Question

Sum of the first nth term of Series

Savindu Pasintha
1 min readDec 23, 2022

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"

Answer

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

1 --> 1 --> "1.00"
2 --> 1 + 1/4 --> "1.25"
5 --> 1 + 1/4 + 1/(4+3*1) + 1/(4+(3*2)) + 1/(4+(3*3)) --> "1.57"


function series(n){
var values = [];
var sum = 0;
if(n != 0){
if(n == 1){
sum = 1;
}else{
for(let i=1; i<=n; i++){
if(i == 1){
sum = 1;
values.push("1")
}else{
if(i == 2){
sum += (1/4)
values.push("1/"+4)
}else{
sum += (1/(4+(3*(i-2))))
values.push("1/"+(4+(3*(i-2))))
}
}
}
}
}
console.log(values,'\n',"sum = "+sum.toFixed(2))
}
series(2);

--

--

No responses yet