- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the sum of first n odd numbers in Python
Suppose we have one number n, we have to find the sum of the first n positive odd numbers.
So, if the input is like 7, then the output will be 49 as [1+3+5+7+9+11+13] = 49
To solve this, we will follow these steps −
- if n is same as 0, then
- return 0
- sum := 1, count := 0, temp := 1
- while count < n-1, do
- temp := temp + 2
- sum := sum + temp
- count := count + 1
- return sum
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): if n == 0: return 0 sum = 1 count = 0 temp = 1 while(count<n-1): temp += 2 sum += temp count += 1 return sum ob = Solution() print(ob.solve(7))
Input
7
Output
49
- Related Articles
- Program to find sum of first N odd numbers in Python
- Find the sum of first $n$ odd natural numbers.
- Swift Program to calculate the sum of first N odd numbers
- Sum of square of first n odd numbers
- 8085 program to find the sum of first n natural numbers
- Program to find sum of first n natural numbers in C++
- Python Program for cube sum of first n natural numbers
- PHP program to find the sum of cubes of the first n natural numbers
- Python Program for Sum of squares of first n natural numbers
- Swift Program to calculate the sum of all odd numbers up to N
- C++ Program to calculate the sum of all odd numbers up to N
- Golang program to calculate the sum of all odd numbers up to N
- PHP program to find the sum of the 5th powers of first n natural numbers
- Sum of first n natural numbers in C Program
- Swift Program to calculate the sum of first N even numbers

Advertisements