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)
1using System;
2
3public class CountOdds {
4 public static int CountOdds(int low, int high) {
5 return (high + 1) / 2 - low / 2;
6 }
7
8 public static void Main() {
9 int low = 3, high = 7;
10 Console.WriteLine(CountOdds(low, high));
11 }
12}
This C# example leverages integer division to calculate the odd count efficiently between the provided low and high values, ensuring correctness with the inclusive range by the high + 1
adjustment.
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
The Python solution iterates over the range from low to high, incrementing a count for every odd number determined by the modulus operator.