Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Sum of squares of first n natural numbers
Next article icon

Program for Sum of squares of first n natural numbers

Last Updated : 29 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a positive integer n, we have to find the sum of squares of first n natural numbers. 
Examples : 

Input : n = 2
Output: 5
Explanation: 1^2+2^2 = 5

Input : n = 8
Output: 204
Explanation : 1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 = 204

[Naive Approach] – Adding One By One – O(n) Time and O(1) Space

The idea for this naive approach is to run a loop from 1 to n and sum up all the squares. 

C++
#include <iostream> using namespace std;  int summation(int n) {     int sum = 0;     for (int i = 1; i <= n; i++)         sum += (i * i);      return sum; }  int main() {     int n = 2;     cout << summation(n);     return 0; } 
C
#include <stdio.h>   int summation(int n) {     int sum = 0;     for (int i = 1; i <= n; i++)         sum += (i * i);     return sum; }  int main() {     int n = 2;     printf("%d",summation(n));     return 0; } 
Java
import java.util.*; import java.lang.*;  class GfG  {      public static int summation(int n)     {         int sum = 0;         for (int i = 1; i <= n; i++)             sum += (i * i);          return sum;     }       public static void main(String args[])     {         int n = 2;         System.out.println(summation(n));     } } 
Python
def summation(n):     return sum([i**2 for i in                 range(1, n + 1)])  if __name__ == "__main__":     n = 2     print(summation(n)) 
C#
using System; class GfG  {      public static int summation(int n)     {         int sum = 0;         for (int i = 1; i <= n; i++)             sum += (i * i);          return sum;     }      public static void Main()     {         int n = 2;          Console.WriteLine(summation(n));     } } 
JavaScript
function summation(n) {     let sum = 0;     for (let i = 1; i <= n; i++)         sum += (i * i);      return sum; }   let n = 2; console.log(summation(n)); 

Output
5

[Expected Approach]- Using Mathematical Formulae – O(1) Time and O(1) Space

The idea for this approach is to use the mathematical formulae for the sum of squares of first n natural numbers.

12 + 22 + ……… + n2 = n(n+1)(2n+1) / 6

We can prove this formula using induction. We can easily see that the formula is true for n = 1 and n = 2 as sums are 1 and 5 respectively.

Let it be true for n = k-1. So sum of k-1 numbers
is (k – 1) * k * (2 * k – 1)) / 6

In the following steps, we show that it is true
for k assuming that it is true for k-1.

Sum of k numbers = Sum of k-1 numbers + k2
= (k – 1) * k * (2 * k – 1) / 6 + k2
= ((k2 – k) * (2*k – 1) + 6k2)/6
= (2k3 – 2k2 – k2 + k + 6k2)/6
= (2k3 + 3k2 + k)/6
= k * (k + 1) * (2*k + 1) / 6

Example : Find sum of squares of the first 3 natural numbers
Solution:
= 3 * (3 + 1) * (2*3 + 1) / 6
= (3 * 4 * 7) / 6
= 84 / 6
= 14

C++
#include <iostream> using namespace std;   int summation(int n) {     return (n * (n + 1) *          (2 * n + 1)) / 6; }  int main() {     int n = 10;     cout << summation(n) << endl;     return 0; } 
C
#include <stdio.h>   int summation(int n) {     return (n * (n + 1) *             (2 * n + 1)) / 6; }  int main() {     int n = 10;     printf("%d", summation(n));     return 0; } 
Java
import java.util.*; import java.lang.*;  class GFG  {      public static int summation(int n)     {         return (n * (n + 1) *                 (2 * n + 1)) / 6;     }       public static void main(String args[])     {         int n = 10;         System.out.println(summation(n));     } } 
Python
# Python code to find sum of  # squares of first n natural numbers. def summation(n):     return (n * (n + 1) *             (2 * n + 1)) / 6      # Driver Code if __name__ == '__main__':     n = 10     print(summation(n)) 
C#
using System;  class GFG  {       public static int summation(int n)     {         return (n * (n + 1) *                 (2 * n + 1)) / 6;     }       public static void Main()     {         int n = 10;          Console.WriteLine(summation(n));     } } 
JavaScript
function summation(n) {     return (n * (n + 1) * (2 * n + 1)) / 6; }  let n = 10; console.log(summation(n)); 

Output
385


Avoiding the overflow: 
In the above method, sometimes due to large value of n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid this overflow up to some extent using the fact that n*(n+1) must be divisible by 2 and restructuring the formula as (n * (n + 1) / 2) * (2 * n + 1) / 3;

C++
#include <iostream> using namespace std;   int summation(int n) { //to avoid overflow  //n*(n + 1)*(2 * n + 1) / 6 = (n * (n + 1) / 2) * (2 * n + 1) / 3;     return (n * (n + 1) / 2) * (2 * n + 1) / 3; }   int main() {     int n = 10;     cout << summation(n) << endl;     return 0; } 
Java
import java.io.*;  class GFG {     static int summation(int n)   {     //to avoid overflow      //n*(n + 1)*(2 * n + 1) / 6 = (n * (n + 1) / 2) * (2 * n + 1) / 3;     return (n * (n + 1) / 2) * (2 * n + 1) / 3;   }    public static void main (String[] args) {     int n = 10;     System.out.println(summation(n));    } } 
Python
def summation(n):     #to avoid overflow      #n*(n + 1)*(2 * n + 1) / 6 = (n * (n + 1) / 2) * (2 * n + 1) / 3;     return (n * (n + 1) // 2) * (2 * n + 1) // 3  def main():     n = 10     print(summation(n))  if __name__ == "__main__":     main() 
C#
using System; class MainClass  {    public static int Summation(int n)   {     //to avoid overflow      //n*(n + 1)*(2 * n + 1) / 6 = (n * (n + 1) / 2) * (2 * n + 1) / 3;     return (n * (n + 1) / 2) * (2 * n + 1) / 3;   }    public static void Main(string[] args)   {     int n = 10;     Console.WriteLine(Summation(n));   } } 
JavaScript
function summation(n) {     //to avoid overflow      //n*(n + 1)*(2 * n + 1) / 6 = (n * (n + 1) / 2) * (2 * n + 1) / 3;     return (n * (n + 1) / 2) * (2 * n + 1) / 3; }  n = 10; console.log(summation(n)); 

Output
385


Next Article
Sum of squares of first n natural numbers

R

Rahul_ and KANCHAN RAY
Improve
Article Tags :
  • DSA
  • Mathematical
  • number-theory
  • series
Practice Tags :
  • Mathematical
  • number-theory
  • series

Similar Reads

  • Sum of squares of first n natural numbers
    Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2. Examples : Input : N = 4Output : 3012 + 22 + 32 + 42= 1 + 4 + 9 + 16= 30Input : N = 5Output : 55Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum. Below is the implementati
    11 min read
  • Sum of square-sums of first n natural numbers
    Given a positive integer n. The task is to find the sum of the sum of square of first n natural number. Examples : Input : n = 3Output : 20Sum of square of first natural number = 1Sum of square of first two natural number = 1^2 + 2^2 = 5Sum of square of first three natural number = 1^2 + 2^2 + 3^2 =
    7 min read
  • Program for cube sum of first n natural numbers
    Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples : Input : n = 5 Output : 225 13 + 23 + 33 + 43 + 53 = 225 Input : n = 7 Output : 784 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784 Recommended PracticeSum of first n terms Try It! A simple solution is to one by one add terms. C
    9 min read
  • Sum of fourth powers of first n odd natural numbers
    Write a program to find sum of fourth power of first n odd natural numbers. 14 + 34 + 54 + 74 + 94 + 114 .............+(2n-1)4. Examples: Input : 3 Output : 707 14 +34 +54 = 707 Input : 6 Output : 24310 14 + 34 + 54 + 74 + 94 + 114 Naive Approach: - In this Simple finding the fourth power of the fir
    8 min read
  • Sum of fourth powers of the first n natural numbers
    Write a program to find the sum of fourth powers of the first n natural numbers 14 + 24 + 34 + 44 + …….+ n4 till n-th term.Examples : Input : 4 Output : 354 14 + 24 + 34 + 44 = 354 Input : 6 Output : 2275 14 + 24 + 34 + 44+ 54+ 64 = 2275 Naive Approach :- Simple finding the fourth powers of the firs
    7 min read
  • Sum of kth powers of first n natural numbers
    Given two integers n and k, the task is to calculate and print 1k + 2k + 3k + ... + nk.Examples: Input: n = 5, k = 2 Output: 55 12 + 22 + 32 + 42 + 52 = 1 + 4 + 9 + 16 + 25 = 55Input: n = 10, k = 4 Output: 25333 Approach: Proof for sum of squares of first n natural numbers: (n+1)3 - n3 = 3 * (n2) +
    13 min read
  • Sum of fourth power of first n even natural numbers
    Write a program to find the sum of fourth power of first n even natural numbers. 24 + 44 + 64 + 84 + 104 +.........+2n4 Examples: Input: 3Output: 156824 +44 +64 = 1568 Input: 6Output: 3640024 + 44 + 64 + 84 + 104 + 124 Naive Approach :- In this Simple finding the fourth powers of the first n even na
    7 min read
  • Sum of sum-series of first N Natural numbers
    Given a natural number n, find the sum of the sum-series of the first N natural number. Sum-Series: is sum of first N natural numbers, i.e, sum-series of 5 is 15 ( 1 + 2 + 3 + 4 + 5 ). Natural number123456Sum of natural number (sum-series)136101521Sum of sum-series1410203556 Example: Input: N = 5 Ou
    6 min read
  • Sum of alternating sign Squares of first N natural numbers
    Given a number N, the task is to find the sum of alternating sign squares of first N natural numbers, i.e., 12 - 22 + 32 - 42 + 52 - 62 + .... Examples: Input: N = 2 Output: 5 Explanation: Required sum = 12 - 22 = -1 Input: N = 8 Output: 36 Explanation: Required sum = 12 - 22 + 32 - 42 + 52 - 62 + 7
    8 min read
  • Program to find sum of first n natural numbers
    Given a number n, find the sum of the first n natural numbers. Examples : Input: n = 3Output: 6Explanation: Note that 1 + 2 + 3 = 6Input : 5Output : 15 Explanation : Note that 1 + 2 + 3 + 4 + 5 = 15 [Naive Approach] Loop Based Summation Calculate the sum of all integers from 1 to n by iterating thro
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences