Horje
Sum of square of first n odd numbers

Given a number n, find sum of square of first n odd natural numbers.

Examples : 

Input : 3
Output : 35 
12 + 32 + 52 = 35

Input : 8
Output : 680
12 + 32 + 52 + 72 + 92 + 112 + 132 + 152 
Recommended Practice

A simple solution is to traverse through n odd numbers and find the sum of square. 

Below is the implementation of the approach.  

C++

<?php
// Simple PHP method to find sum
// of square of first n odd numbers.
 
function squareSum( $n)
{
    $sum = 0;
    for ($i = 1; $i <= $n; $i++)
        $sum += (2*$i - 1) * (2*$i - 1);
    return $sum;
}
 
 
    echo squareSum(8);
 
// This code is contributed by Vt_m.
?>

Javascript

<?php
// Efficient PHP method to find sum of
// square of first n odd numbers.
 
function squareSum($n)
{
    return $n * (4 * $n * $n - 1) / 3;
}
 
 
    echo squareSum(8);
 
// This code is contributed by Vt_m.
?>

Javascript

<script>
 
// JavaScript program to find sum of
// square of first n odd numbers.
 
    function squareSum(n)
    {
        return n*(4*n*n - 1)/3;
    }
 
// Driver code
 
            document.write(squareSum(8));
 
</script>

Output : 

680

Time Complexity: O(1), the code will run in a constant time.
Auxiliary Space: O(1), no extra space is required, so it is a constant.




Reffered: https://www.geeksforgeeks.org


Mathematical

Related
Sum of square of first n even numbers Sum of square of first n even numbers
Number of terms in Geometric Series with given conditions Number of terms in Geometric Series with given conditions
Palindromic Selfie Numbers Palindromic Selfie Numbers
Maximum rational number (or fraction) from an array Maximum rational number (or fraction) from an array
Average of odd numbers till a given odd number Average of odd numbers till a given odd number

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15