Program to count odd numbers in an interval range using Python


Suppose we have two non-negative numbers left and right. We have to find the number of odd numbers between left and right (inclusive).

So, if the input is like left = 3, right = 15, then the output will be 7 because there are 7 odd numbers in range, these are [3,5,7,9,11,13,15], there are 7 elements.

To solve this, we will follow these steps −

  • if left is odd or right is odd, then

    • return 1 + quotient of (right-left) / 2

  • otherwise,

    • return quotient of (right-left) / 2

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(left, right):
   if left % 2 == 1 or right % 2 == 1:
      return (right-left) // 2 + 1
   else:
      return (right-left) // 2

left = 3
right = 15
print(solve(left, right))

Input

3, 15

Output

7

Updated on: 17-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements