Sum of cubes of first n even numbers
Given a number n, find the sum of first n even natural numbers.
Examples:
Input : 2
Output : 72
2^3 + 4^3 = 72
Input : 8
Output :10368
2^3 + 4^3 + 6^3 + 8^3 + 10^3 + 12^3 + 14^3 + 16^3 = 10368
A simple solution is to traverse through n even numbers and find the sum of cubes.
C++
#include <iostream>
using namespace std;
int cubeSum( int n)
{
int sum = 0;
for ( int i = 1; i <= n; i++)
sum += (2*i) * (2*i) * (2*i);
return sum;
}
int main()
{
cout << cubeSum(8);
return 0;
}
|
Java
public class GFG
{
public static int cubesum( int n)
{
int sum = 0 ;
for ( int i = 1 ; i <= n; i++)
sum += ( 2 * i) * ( 2 * i)
* ( 2 * i);
return sum;
}
public static void main(String args[])
{
int a = 8 ;
System.out.println(cubesum(a));
}
}
|
Python3
def cubeSum(n):
sum = 0
for i in range ( 1 , n + 1 ):
sum + = ( 2 * i) * ( 2 * i) * ( 2 * i)
return sum
print (cubeSum( 8 ))
|
C#
using System;
public class GFG
{
public static int cubesum( int n)
{
int sum = 0;
for ( int i = 1; i <= n; i++)
sum += (2 * i) * (2 * i)
* (2 * i);
return sum;
}
public static void Main()
{
int a = 8;
Console.WriteLine(cubesum(a));
}
}
|
PHP
<?php
function cubeSum( $n )
{
$sum = 0;
for ( $i = 1; $i <= $n ; $i ++)
$sum += (2 * $i ) *
(2 * $i ) *
(2 * $i );
return $sum ;
}
echo cubeSum(8);
?>
|
Javascript
<script>
function cubeSum(n)
{
let sum = 0;
for (let i = 1; i <= n; i++)
sum += (2*i) * (2*i) * (2*i);
return sum;
}
document.write(cubeSum(8));
</script>
|
Output:
10368
Time Complexity: O(n)
Auxiliary Space: O(1)
An efficient solution is to apply below formula.
sum = 2 * n2(n+1)2
How does it work?
We know that sum of cubes of first
n natural numbers is = n2(n+1)2 / 4
Sum of cubes of first n natural numbers =
2^3 + 4^3 + .... + (2n)^3
= 8 * (1^3 + 2^3 + .... + n^3)
= 8 * n2(n+1)2 / 4
= 2 * n2(n+1)2
Example
C++
#include <iostream>
using namespace std;
int cubeSum( int n)
{
return 2 * n * n * (n + 1) * (n + 1);
}
int main()
{
cout << cubeSum(8);
return 0;
}
|
Java
public class GFG
{
public static int cubesum( int n)
{
return 2 * n * n * (n + 1 ) * (n + 1 );
}
public static void main(String args[])
{
int a = 8 ;
System.out.println(cubesum(a));
}
}
|
Python3
def cubeSum(n):
return 2 * n * n * (n + 1 ) * (n + 1 )
print (cubeSum( 8 ))
|
C#
using System;
class GFG
{
public static int cubesum( int n)
{
return 2 * n * n *
(n + 1) * (n + 1);
}
public static void Main()
{
int a = 8;
Console.WriteLine(cubesum(a));
}
}
|
PHP
<?php
function cubeSum( $n )
{
return 2 * $n * $n *
( $n + 1) * ( $n + 1);
}
echo cubeSum(8);
?>
|
Javascript
<script>
function cubesum(n)
{
return 2 * n * n * (n + 1) * (n + 1);
}
var a = 8;
document.write(cubesum(a));
</script>
|
Output:
10368
Time Complexity: O(1)
Auxiliary Space: O(1)
Sum of cube of first n odd natural numbers
Last Updated :
16 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...