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
Squared sum of n odd numbers - JavaScript
We are required to write a JavaScript function that takes in a Number, say n, and finds the sum of the square of first n odd natural Numbers.
For example, if the input number is 3, we need to find the first 3 odd numbers (1, 3, 5) and calculate the sum of their squares:
1² + 3² + 5² = 1 + 9 + 25 = 35
Understanding the Pattern
The first n odd natural numbers follow the pattern: 1, 3, 5, 7, 9... The formula for the i-th odd number is (2 * i) - 1.
Example
const num = 3;
const squaredSum = num => {
let sum = 0;
for(let i = 1; i <= num; i++){
sum += Math.pow((2 * i) - 1, 2);
};
return sum;
};
console.log(squaredSum(num));
35
Alternative Approach Using Mathematical Formula
There's also a direct mathematical formula: the sum of squares of first n odd numbers equals n(2n-1)(2n+1)/3.
const squaredSumFormula = n => {
return n * (2 * n - 1) * (2 * n + 1) / 3;
};
// Test with different values
console.log(squaredSumFormula(3)); // 35
console.log(squaredSumFormula(5)); // 165
console.log(squaredSumFormula(1)); // 1
35 165 1
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Loop Method | O(n) | O(1) | High |
| Mathematical Formula | O(1) | O(1) | Medium |
Conclusion
Both methods work effectively. The loop approach is more intuitive, while the mathematical formula provides O(1) time complexity for better performance with large inputs.
Advertisements
