JavaScript
// Method 1: Using for loop
let n = 10;
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log("Sum of first", n, "natural numbers:", sum);
// Method 2: Using formula (n × (n + 1)) / 2
let num = 10;
let sumFormula = (num * (num + 1)) / 2;
console.log("Using formula:", sumFormula);
// Method 3: Using while loop
let number = 10;
let total = 0;
let counter = 1;
while (counter <= number) {
total += counter;
counter++;
}
console.log("Using while loop:", total);
// Method 4: Using function
function sumNaturalNumbers(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
console.log("Using function:", sumNaturalNumbers(10));
// Method 5: Using reduce (functional approach)
function sumNaturalNumbersReduce(n) {
return Array.from({length: n}, (_, i) => i + 1)
.reduce((sum, num) => sum + num, 0);
}
console.log("Using reduce:", sumNaturalNumbersReduce(10));Output
Sum of first 10 natural numbers: 55 Using formula: 55 Using while loop: 55 Using function: 55 Using reduce: 55
This program demonstrates different approaches to calculate sum of natural numbers.
Natural Numbers
Positive integers: 1, 2, 3, 4, 5, ...
Method 1: For Loop
Iterative approach:
javascriptlet sum = 0; for (let i = 1; i <= n; i++) { sum += i; }
Compound Assignment
sum += i is shorthand for sum = sum + i
+=: Addition assignment-=: Subtraction assignment*=: Multiplication assignment/=: Division assignment
Method 2: Mathematical Formula
Gauss's formula: n × (n + 1) / 2
javascriptlet sum = (n * (n + 1)) / 2;
Pros:
- O(1) time complexity
- No loop needed
- Most efficient
Example:
Sum of 1 to 10 = (10 × 11) / 2 = 55
Method 3: While Loop
Condition-based iteration:
javascriptwhile (counter <= number) { total += counter; counter++; }
Method 4: Function
Reusable code:
javascriptfunction sumNaturalNumbers(n) { let sum = 0; for (let i = 1; i <= n; i++) { sum += i; } return sum; }
Method 5: Functional Approach (ES6)
Using array methods:
javascriptArray.from({length: n}, (_, i) => i + 1) .reduce((sum, num) => sum + num, 0);
Array.from(): Creates array from iterable
reduce(): Accumulates values
Time Complexity:
- Loop methods: O(n)
- Formula: O(1) - Best!
When to Use:
-
Formula: Best performance
-
Loop: Learning, flexible logic
-
Reduce: Functional programming style