-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEx.4.html
64 lines (58 loc) · 2.12 KB
/
Ex.4.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans+Extra+Condensed" rel="stylesheet">
<title>Document</title>
</head>
<body>
<img src="https://www.codewars.com/users/stefan835/badges/large" alt="codewars-badge">
<h1>Ex.4</h1>
<h3><a href="./Ex.3.html">Link to previos!</a></h3>
<h3><a href="./Ex.5.html">Link to next!</a></h3>
<p>Your task is to write a function which returns the sum of following series upto nth term(parameter).</p>
<i>Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...</i>
<h4>Rules:</h4>
<p>You need to round the answer to 2 decimal places and return it as String.</p>
<p>If the given value is 0 then it should return 0.00</p>
<p>You will only be given Natural Numbers as arguments.</p>
<h4>Examples:</h4>
<i>SeriesSum(1) => 1 = "1.00"<br/>
SeriesSum(2) => 1 + 1/4 = "1.25"<br/>
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"</i>
<h2>My solution</h2>
<div class="code">
<pre>function SeriesSum(n) {<br/> let result = !n ? 0 : 1;<br/> for (let i = 1; i < n; i++) {<br/> result += 1 / (1 + (3 * i))<br/> }<br/> return result.toFixed(2)<br/>}</pre>
</div>
<h2>Best solution</h2>
<div class="code">
<pre>function SeriesSum(n) {<br/> for (var s = 0, i = 0; i < n; i++) {<br/> s += 1 / (1 + i * 3)<br/> }<br/><br/> return s.toFixed(2)<br/>}</pre>
</div>
<h2 class="passed">PASSED</h2>
<h3>Time: 314ms</h3>
<script>
//MY SOLUTION
function SeriesSum(n) {
let result = !n ? 0 : 1;
for (let i = 1; i < n; i++) {
result += 1 / (1 + (3 * i))
}
return result.toFixed(2)
}
console.log(SeriesSum(5))
// SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
//BEST SOLUTION
// function SeriesSum(n) {
// for (var s = 0, i = 0; i < n; i++) {
// s += 1 / (1 + i * 3)
// }
//
// return s.toFixed(2)
// }
</script>
</body>
</html>