Count Odd Numbers in an Interval Range

Problem Description

So, you want to count the odd numbers in a given range? Sounds simple, right? Well, welcome to the world of programming where even the simplest tasks can turn into a brain teaser! Imagine you’re at a party, and you want to count how many odd-numbered guests are there. You know, the ones who always seem to have a quirky story to tell. But instead of just counting them, you decide to write a program. Because why not complicate things?

The problem is straightforward: given two integers, low and high, you need to find out how many odd numbers exist between them, inclusive.

Code Solution


class Solution {
public:
    int countOdds(int low, int high) {
        return (high + 1) / 2 - low / 2;
    }
};

Approach

The approach here is as simple as counting the number of odd socks in your laundry basket. The formula (high + 1) / 2 - low / 2 cleverly calculates the number of odd integers by leveraging the properties of integer division. It counts how many odd numbers are there from 1 to high and subtracts the count of odd numbers from 1 to low - 1. Voilà! You have your answer.

Time and Space Complexity

Time Complexity

O(1) – The solution runs in constant time since it only involves a few arithmetic operations.

Space Complexity

O(1) – No additional space is used that scales with input size.

Real-World Example

Imagine you’re at a carnival, and you’re counting how many odd-numbered rides you can go on. You start at ride number low and end at ride number high. Using our nifty little program, you can quickly find out how many odd-numbered rides are available without having to count them one by one. Just plug in the numbers, and boom! You’re ready to enjoy the rides.

Similar Problems

If you enjoyed this problem, you might want to check out these similar challenges:

Count Even Numbers in an Interval Range Solution in C++