File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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.` ) ;
You can’t perform that action at this time.
0 commit comments