Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sum of the first nth term of Series #2

Open
hellocan opened this issue Apr 7, 2016 · 5 comments
Open

Sum of the first nth term of Series #2

hellocan opened this issue Apr 7, 2016 · 5 comments

Comments

@hellocan
Copy link

hellocan commented Apr 7, 2016

Rules:
You need to round the answer upto 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"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
Your Test Cases:
Test.assertEquals(SeriesSum(1), "1.00")
Test.assertEquals(SeriesSum(2), "1.25")
Test.assertEquals(SeriesSum(3), "1.39")
Test.assertEquals(SeriesSum(4), "1.49")
where -By
http://www.codewars.com/kata/555eded1ad94b00403000071/train/javascript

@Go7hic
Copy link
Member

Go7hic commented Apr 7, 2016

function seriesSum (num) {
  if (num === 0) {
    return '0.00'
  } else {
    var arr = Array(num)
    for (var n = 0;n < arr.length;n ++) {
      arr[n] = 1/(3*n+1);
    }
    return arr.reduce((i,j) => i+j).toFixed(2)
  }
}

直接看题目写的,觉得下次最好把题目的链接也贴出来。这样做完可以进去看看别人怎么做

@hellocan
Copy link
Author

hellocan commented Apr 8, 2016

function SeriesSum(n) { 
     if (n) { 
         var arr = []; 
        for (var i = 0; i < n; i++) {
            var l = 1 / (1 + 3 * i);
            arr.push(l);
        }
        return arr.reduce((i, j) => i + j);
    }
} 

@Go7hic
Copy link
Member

Go7hic commented Apr 8, 2016

没有处理 0 的情况,也没有处理两位小数。

格式就是用 Markdown 的格式。

@Go7hic
Copy link
Member

Go7hic commented Apr 8, 2016

这个题目我傻逼了,虽然答案对了,但是我为了想用数组的迭代方法,特意造了个数组来做,其实完全没必要,直接用累加就够了,虽然时间复杂度一样,但是可以省很多代码,哈哈。下面是排名最高的答案

function seriesSum(n) {
  for (var s = 0, i = 0; i < n; i++) {
    s += 1 / (1 + i * 3)
  }
  return s.toFixed(2)
}

@hellocan hellocan reopened this Apr 10, 2016
@hellocan
Copy link
Author

function SeriesSum(n) { 
    if (n===0) {return '0.00';} 
    else{   
        var arr = []; 
        for (var i = 0; i < n; i++) {
            var l = 1 / (1 + 3 * i);
            arr.push(l);
        }
        return arr.reduce((i, j) => i + j).toFixed(2);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants