Sponsored
Sponsored
This approach uses the mathematical properties of odd and even numbers. The core idea is to count the odd numbers in the range efficiently without iterating through all numbers.
Two cases arise:
- If both low and high are odd, then the range includes both `low` and `high` as odd numbers.
- Otherwise, depending on whether `low` or `high` is even, you adjust the start or the end.
The formula used is derived from these observations:
If either `low` or `high` is odd, the count is `(high - low) / 2 + 1`. Otherwise, it is `(high - low) / 2`.
Time Complexity: O(1)
Space Complexity: O(1)
1#include <iostream>
2using namespace std;
3
4int countOdds(int low, int high) {
5 return ((high + 1) / 2) - (low / 2);
6}
7
8int main() {
9 int low = 3, high = 7;
10 cout << countOdds(low, high) << endl;
11 return 0;
12}
This C++ solution is similar to the C solution. It uses integer division to compute the number of odds efficiently.
In this approach, we iterate through the numbers from low to high and check if each number is odd by using the modulus operator. Count every number that meets the condition of being odd.
This approach, though straightforward, is less optimal for larger ranges due to its linear nature in terms of time complexity.
Time Complexity: O(n), where n is (high - low + 1)
Space Complexity: O(1)
1
This Java solution iterates through numbers from low to high to count how many of them are odd, using a simple loop structure with modulus checking.