Nicomachus’s Theorem
Last Updated :
17 Jan, 2023
Nicomachus’s Theorem states that sum of cubes of first n natural numbers is equal to squares of natural number sum.
In other words
Or we can say that the sum is equal to square of n-th triangular number.
Mathematical Induction based proof can be found here.
C++
#include <bits/stdc++.h>
using namespace std;
void NicomachusTheorem_sum( int n)
{
int sum = 0;
for ( int k=1; k<=n; k++)
sum += k*k*k;
int triNo = n*(n+1)/2;
if (sum == triNo * triNo)
cout << "Yes" ;
else
cout << "No" ;
}
int main()
{
int n = 5;
NicomachuTheorem_sum(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void NicomachuTheorem_sum( int n)
{
int sum = 0 ;
for ( int k = 1 ; k <= n; k++)
sum += k * k * k;
int triNo = n * (n + 1 ) / 2 ;
if (sum == triNo * triNo)
System.out.println( "Yes" );
else
System.out.println( "No" );
}
public static void main (String[] args)
{
int n = 5 ;
NicomachuTheorem_sum(n);
}
}
|
Python3
def NicomachuTheorem_sum(n):
sum = 0 ;
for k in range ( 1 , n + 1 ):
sum + = k * k * k;
triNo = n * (n + 1 ) / 2 ;
if ( sum = = triNo * triNo):
print ( "Yes" );
else :
print ( "No" );
n = 5 ;
NicomachuTheorem_sum(n);
|
C#
using System;
class GFG {
static void NicomachuTheorem_sum( int n)
{
int sum = 0;
for ( int k = 1; k <= n; k++)
sum += k * k * k;
int triNo = n * (n + 1) / 2;
if (sum == triNo * triNo)
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
public static void Main ()
{
int n = 5;
NicomachuTheorem_sum(n);
}
}
|
PHP
<?php
function NicomachuTheorem_sum( $n )
{
$sum = 0;
for ( $k = 1; $k <= $n ; $k ++)
$sum += $k * $k * $k ;
$triNo = $n * ( $n + 1) / 2;
if ( $sum == $triNo * $triNo )
echo "Yes" ;
else
echo "No" ;
}
$n = 5;
NicomachuTheorem_sum( $n );
?>
|
Javascript
<script>
function NicomachuTheorem_sum(n)
{
let sum = 0;
for (let k = 1; k <= n; k++)
sum += k * k * k;
let triNo = n * (n + 1) / 2;
if (sum == triNo * triNo)
document.write( "Yes" );
else
document.write( "No" );
}
let n = 5;
NicomachuTheorem_sum(n);
</script>
|
Time complexity : O(n)
Auxiliary Space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...