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 <stdio.h>
2
3int countOdds(int low, int high) {
4 return ((high + 1) / 2) - (low / 2);
5}
6
7int main() {
8 int low = 3, high = 7;
9 printf("%d\n", countOdds(low, high));
10 return 0;
11}
This C solution uses integer arithmetic to calculate the number of odd numbers directly. The expression (high + 1) / 2
gives the count of odd numbers from 1 to high, and low / 2
gives the count of odd numbers from 1 up to just below low. Their difference provides the count of odd numbers between low and high.
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 JavaScript solution iterates through each integer from low to high and utilizes the modulus operator to identify and count odd numbers.