Program to find the sum of a Series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + … + (n*n)
You have been given a series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + … + (n*n), find out the sum of the series till nth term.
Examples :
Input : n = 3
Output : 14
Explanation : (1*1) + (2*2) + (3*3)
Input : n = 5
Output : 55
Explanation : (1*1) + (2*2) + (3*3) + (4*4) + (5*5)
C++
#include<iostream>
using namespace std;
int Series( int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
int main()
{
int n = 3;
int res = Series(n);
cout<<res<<endl;
}
|
C
#include <stdio.h>
int Series( int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
int main()
{
int n = 3;
int res = Series(n);
printf ( "%d" , res);
}
|
Java
import java.io.*;
class GFG {
static int Series( int n)
{
int i;
int sums = 0 ;
for (i = 1 ; i <= n; i++)
sums += (i * i);
return sums;
}
public static void main(String[] args)
{
int n = 3 ;
int res = Series(n);
System.out.println(res);
}
}
|
Python
def Series(n):
sums = 0
for i in range ( 1 , n + 1 ):
sums + = (i * i);
return sums
n = 3
res = Series(n)
print (res)
|
C#
using System;
class GFG {
static int Series( int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
public static void Main()
{
int n = 3;
int res = Series(n);
Console.Write(res);
}
}
|
PHP
<?php
function Series( $n )
{
$i ;
$sums = 0;
for ( $i = 1; $i <= $n ; $i ++)
$sums += ( $i * $i );
return $sums ;
}
$n = 3;
$res = Series( $n );
echo ( $res );
?>
|
Javascript
<script>
function Series( n) {
let i;
let sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
let n = 3;
let res = Series(n);
document.write(res);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Efficient Approach:
As we know the sum of squares of the first N natural numbers = (N*(N+1)*(2*N+1))/6.
Below is the implementation of this approach:
C++
#include<iostream>
using namespace std;
int Series( int n)
{
return (n * (n + 1) * (2 * n + 1)) / 6;
}
int main()
{
int n = 3;
int res = Series(n);
cout<<res<<endl;
}
|
Java
import java.io.*;
class GFG {
static int Series( int n)
{
return (n * (n + 1 ) * ( 2 * n + 1 )) / 6 ;
}
public static void main (String[] args) {
int n = 3 ;
int res = Series(n);
System.out.println(res);
}
}
|
Python3
def Series(n):
return (n * (n + 1 ) * ( 2 * n + 1 )) / 6
n = 3
res = Series(n)
print ( int (res))
|
C#
using System;
public class GFG {
static int Series( int n)
{
return (n * (n + 1) * (2 * n + 1)) / 6;
}
static public void Main()
{
int n = 3;
Console.Write(Series(n));
}
}
|
Javascript
function Series(n)
{
return (n * (n + 1) * (2 * n + 1)) / 6;
}
let n = 3;
console.log(Series(n));
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Please refer below post for O(1) solution.
Sum of squares of first n natural numbers
Last Updated :
08 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...