Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 −
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
Advertisements
