Skip to content

Commit f6ca244

Browse files
author
wakidurrahman
committed
sum of all numbers
1 parent d4850fc commit f6ca244

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* https://stackoverflow.com/questions/29549836/how-to-find-the-sum-of-all-numbers-between-1-and-n-using-javascript
3+
* *** How to find the sum of all numbers between 1 and N using JavaScript.
4+
* *** I'm trying to find a way to calculate the sum of all numbers between 1 to N using JavaScript.
5+
* The following is the code I have tried so far but it doesn't seem to work.
6+
* *** Suppose we want to write a function that calculates the sum of all numbers from 1 up to (an including) some number n.
7+
*
8+
*/
9+
10+
// Implementation 1:
11+
function numberSum(N) {
12+
var total = 0;
13+
for (var i = 1; i <= N; i++) {
14+
total += i;
15+
}
16+
return total;
17+
}
18+
19+
// Implementation 2:
20+
var res = (n * (n + 1)) / 2;
21+
22+
23+
let t1 = performance.now();
24+
numberSum(1000000000);
25+
let t2 = performance.new();
26+
console.log(`Time Elapsed: ${(t2-t1)/100} seconds.`);

0 commit comments

Comments
 (0)