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

 Live Demo

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

Updated on: 06-Oct-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements