Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Mathematics summation function in JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should return the sum of all the natural numbers from 1 to n including both 1 and n.
Example
Following is the code ?
const num = 34;
const summation = (num = 1) => {
let res = 0;
for(let i = 1; i <= num; i++){
res += i;
};
return res;
};
console.log(summation(num));
Output
Following is the console output ?
595
Using Mathematical Formula (Optimized)
Instead of using a loop, we can use the mathematical formula for the sum of first n natural numbers: n × (n + 1) / 2
const summationFormula = (num) => {
return (num * (num + 1)) / 2;
};
console.log(summationFormula(34)); // Same result
console.log(summationFormula(100)); // Testing with larger number
595 5050
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Loop Method | O(n) | Small numbers, learning purposes |
| Mathematical Formula | O(1) | Large numbers, performance critical |
Conclusion
Both methods calculate the sum of natural numbers effectively. The mathematical formula approach is more efficient with O(1) time complexity, while the loop method is easier to understand for beginners.
Advertisements
