Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Sum of squares of first N natural numbers - Python
Next article icon

Sum of squares of first N natural numbers - Python

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to calculate the sum of squares of the first n natural numbers. The sum of squares is the result of adding up the squares of each number from 1 to n. For example, if n = 5, the sum of squares would be 12 + 22 + 32+ 42+52=55. Let's explore different methods to compute this sum efficiently.

Using mathematical formula

This method uses mathematical formula to directly compute the sum of squares of the first n natural numbers. It is the most efficient and fastest approach since it avoids any iteration and performs the calculation in constant time.

Mathematical_formula
Mathematical Formula
Python
n = 5 res = n * (n + 1) * (2 * n + 1) // 6 print(res) 

Output
55 

Explanation: For n = 5, the expression becomes 5 * 6 * 11 // 6, which equals 330 // 6, giving the final result 55. The // operator performs integer division, ensuring the result is returned as a whole number without any decimal part.

Using generator expression

Generator expression inside the built-in sum() function to calculate the square of each number and sum them. It’s simple and memory-efficient because it doesn't store all the values in memory (unlike a list comprehension).

Python
n = 5 res = sum(x * x for x in range(1, n + 1)) print(res)  

Output
55 

Explanation: Generator function generates the square of each number x in the range from 1 to n. For n = 5, it calculates 1² + 2² + 3² + 4² + 5², resulting in 55.

Using reduce

reduce() function from Python’s functools module applies a lambda function cumulatively to the items of the sequence, reducing them to a single value here, summing up the squares of numbers.

Python
from functools import reduce  n = 5 res = reduce(lambda x, y: x + y * y, range(1, n + 1), 0) print(res) 

Output
55 

Explanation: reduce() applies the lambda x + y * y to the numbers from 1 to n, starting with 0. For n = 5, it calculates 0 + 1² + 2² + 3² + 4² + 5², resulting in 55. In each step, y is squared and added to the accumulated total x, effectively summing the squares.

Using for loop

This is the most traditional and beginner-friendly method. It uses a simple for loop to iterate from 1 to n, calculating the square of each number and adding it to the total.

Python
n = 5 total = 0  for i in range(1, n + 1):     total += i * i print(total) 

Output
55 

Explanation: For loop iterates over each number from 1 to n and for each number i, it calculates i * i and adds it to the running total. For n = 5, the loop calculates 1² + 2² + 3² + 4² + 5², resulting in 55.

Related Articles

  • Generator expression
  • reduce()
  • for loop

Next Article
Sum of squares of first N natural numbers - Python

K

kartik
Improve
Article Tags :
  • DSA
  • Python Programs

Similar Reads

    Python Program for cube sum of first n natural numbers
    We are given a number n and we need to print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till the n-th term in python.Examples:Input: n = 5Output: 225Explanation: 13 + 23 + 33 + 43 + 53 = 225Let's discuss some of the ways to do it.Using Mathematical Formula: Most efficient solution is to use t
    2 min read
    Python | Sum of squares in list
    Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let's discuss
    5 min read
    Python Program to Find the Sum of Natural Numbers Using While Loop
    Calculating the Sum of N numbers in Python using while loops is very easy. In this article, we will understand how we can calculate the sum of N numbers in Python using while loop.Calculate Sum of Natural Numbers in Python Using While LoopBelow are some of the examples by which we can see how we can
    2 min read
    Python program to calculate square of a given number
    The task of calculating the square of a number in Python involves determining the result of multiplying a number by itself. For example, given the number 4, its square is 16 because 4 × 4 = 16.Using ** operatorexponentiation operator (**) is the most direct and optimized way to compute powers. Since
    1 min read
    Python | Product of Squares in List
    Python being the language of magicians can be used to perform many tedious and repetitive tasks in an easy and concise manner and have the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding product of squares of list in just one line. Let’s disc
    5 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