Skip to content

Commit 73f511a

Browse files
add up to n numbers program added
1 parent 4e2140a commit 73f511a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Random-Questions/add-up-to-n.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const n = 10;
2+
3+
/**
4+
*
5+
* @param {*} n Integer
6+
* Time complexity = O(n)
7+
* Space complexity = O(1)
8+
*/
9+
const addUpTo = (n) => {
10+
if (typeof n != 'number') {
11+
console.warn('Only numbers allowed')
12+
}
13+
let sum = 0
14+
for (let i = 1; i <= n; i++) {
15+
sum += i
16+
}
17+
console.log(`Result: ${sum}`);
18+
}
19+
console.info(`------------ Program with O(n) ------------`)
20+
addUpTo(n)
21+
22+
const addUpToOpt = (n) => {
23+
if (typeof n != 'number') {
24+
console.warn('Only numbers allowed')
25+
}
26+
const sum = n*(n+1)/2
27+
console.log(`Result: ${sum}`);
28+
}
29+
console.info(`------------ Program with O(1) ------------`)
30+
addUpToOpt(n)

0 commit comments

Comments
 (0)