Daily Coding Challenge: Sum of the first nth term of Series – written in JavaScript, Python and Java

Posted by

Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. I’ve decided that I am going to post my solutions here written in JavaJavaScript and Python for all of my readers to learn! Please let me know if you have any questions.

Sum of the first nth term of Series

Task:

Your task is to write a function which returns the sum of following series up to 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:

SeriesSum(1) => 1 = "1.00"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"

JavaScript:

function SeriesSum(n) {
  if (n === 0) {
    return '0.00';
  } else if (n === 1) {
    return '1.00';
  } else {
    let sum = 1;
    let count = 1;
    for (let i = 1; i < n; i++) {
      count += 3;
      let frac = '1/' + count.toString().split('/');
      let split = frac.split('/');
      let result = parseInt(split[0], 10) / parseInt(split[1], 10);
      sum += Number(result);
    }
    return sum.toFixed(2);
  }
}

Python:

def series_sum(n):
    if n == 0:
        return '0.00'
    else:
        sum = 0;
        for i in range(n):
            sum += 1 / (1 + i * 3)
        return format(sum, '.2f')

Java:

public class NthSeries {
	
    public static String seriesSum(int n) {
        Double sum = 0.00;
        if (n == 0) {
            return String.valueOf(sum);
        } else {
            for (Integer i = 0; i < n; i++) {
                sum += Double.valueOf(1) / Double.valueOf(1 + i * 3);
            }
            return String.format("%.2f", sum);
        }
    }
}

Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*