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)
1function countOdds(low, high) {
2 return Math.floor((high + 1) / 2) - Math.floor(low / 2);
3}
4
5const low = 3, high = 7;
6console.log(countOdds(low, high));
This JavaScript solution uses Math.floor
for integer division and operates in constant time to find the number of odd numbers within the range specified.
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 C solution uses a for-loop to iterate between the low and high values, incrementing a counter whenever it encounters an odd number as determined by the modulus operator.