- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Python Program for Sum of squares of first n natural numbers
In this article, we will learn about the solution and approach to solve the given problem statement.
Given a positive integer N as input . We need to compute the value of 12 + 22 + 32 + ….. + N2.
Problem statement:This can be solved by two methods
- Multiplication addition arithmetic
- Using mathematical formula
Approach 1: Multiplication & Addition Arithmetic
Here we run a loop from 1 to n and for each i, 1 <= i <= n, find i2 and add to sm.
def sqsum(n) : sm = 0 for i in range(1, n+1) : sm = sm + pow(i,2) return sm # main n = 5 print(sqsum(n))
Approach 2: By using mathematical formulae
As we all know that the sum of squares of natural numbers is given by the formula −
(n * (n + 1) * (2 * n + 1)) // 6n * (n + 1) * (2 * n + 1)) // 6 (n * (n + 1) * (2 * n + 1)) // 6(n * (n + 1) * (2 * n + 1)) // 6
def squaresum(n) : return (n * (n + 1) * (2 * n + 1)) // 6 # Driven Program n = 10 print(squaresum(n))
In this article, we learned about the approach to find the Sum of squares of first n natural numbers.
- Related Articles
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Python Program for cube sum of first n natural numbers
- Java Program to calculate Sum of squares of first n natural numbers
- C++ Program for cube sum of first n natural numbers?
- C Program for cube sum of first n natural numbers?
- Difference between sum of the squares of and square of sum first n natural numbers.
- C Program for the cube sum of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Sum of squares of the first n even numbers in C Program
- Java Program to cube sum of first n natural numbers
- Java Program to Display Numbers and Sum of First N Natural Numbers
- Sum of sum of first n natural numbers in C++
- 8085 program to find the sum of first n natural numbers