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)
1public class CountOdds {
2 public static int countOdds(int low, int high) {
3 return (high + 1) / 2 - low / 2;
4 }
5
6 public static void main(String[] args) {
7 int low = 3, high = 7;
8 System.out.println(countOdds(low, high));
9 }
10}
This Java solution makes use of simple integer arithmetic to directly determine the count of odd numbers within the specified range. The addition of 1 to high before division works with inclusive ranges seamlessly.
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.