Difference between Sum of Cubes and Sum of First N Natural Numbers
Last Updated :
28 Mar, 2022
Given an integer N, find the absolute difference between sum of the cubes of first N natural numbers and the sum of first N natural numbers.
Input: N = 3
Output: 30
Sum of first three numbers is 3 + 2 + 1 = 6
Sum of Cube of first three numbers is = 1 + 8 + 27 = 36
Absolute difference = 36 - 6 = 30
Input: N = 5
Output: 210
Approach:
- The sum of the cube of first N natural numbers, using the formula:
- The sum of first N numbers, using the formula:
- The absolute difference between both the sums is
where
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int difference( int n)
{
int S, res;
S = (n * (n + 1)) / 2;
res = S * (S - 1);
return res;
}
int main()
{
int n = 5;
cout << difference(n);
return 0;
}
|
Java
class GFG
{
static int difference( int n)
{
int S, res;
S = (n * (n + 1 )) / 2 ;
res = S * (S - 1 );
return res;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.print(difference(n));
}
}
|
Python3
def difference(n) :
S = (n * (n + 1 )) / / 2 ;
res = S * (S - 1 );
return res;
if __name__ = = "__main__" :
n = 5 ;
print (difference(n));
|
C#
using System;
class GFG
{
static int difference( int n)
{
int S, res;
S = (n * (n + 1)) / 2;
res = S * (S - 1);
return res;
}
static public void Main ()
{
int n = 5;
Console.Write(difference(n));
}
}
|
Javascript
<script>
function difference(n)
{
let S, res;
S = Math.floor((n * (n + 1)) / 2);
res = S * (S - 1);
return res;
}
let n = 5;
document.write(difference(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...