When given a number n, the goal is to find the sum of the firstn natural numbers. For example, if n is 3, we want to calculate 1 + 2 + 3, which equals 6.
1. Using a Mathematical Formula.
function fun1():
function fun1(n) { return n * (n + 1) / 2; } console.log("Ex - 1 >>> ", fun1(3)); // Output: 6
2. Using a Loop.
function fun2():
function fun2(n) { let sum = 0; for (var i = 0; i <= n; i++) { sum = sum + i; console.log(i); } return sum; } console.log("Ex - 2 >>> ", fun2(3)); // Output: 6
For n = 3, the loop runs as
i = 0, sum = 0 + 0 = 0
i = 1, sum = 0 + 1 = 1
i = 2, sum = 1 + 2 = 3
i = 3, sum = 3 + 3 = 6
This approach is straightforward and easy to understand but can be less efficient for very large n compared to the mathematical formula.
Both methods achieve the same result but in different ways.
3.Summing Using Nested Loops
function fun3():
function fun3(n) { let sum = 0; for (let i = 0; i <= n; i++) { for (let j = 0; j <= i; j++) { sum++; } } return sum; } console.log(fun3(3)); // Output: 10
To understand how this works, let's break down the steps when n = 3:
So, sum goes through these steps:
Initial sum = 0
After i = 0, sum = 1
After i = 1, sum = 3
After i = 2, sum = 6
After i = 3, sum = 10
Therefore, fun3(3) returns 10, which is the total number of increments performed.
The above is the detailed content of Summing Numbers in JavaScript with Different Techniques.. For more information, please follow other related articles on the PHP Chinese website!