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
Advertisements