Count Odd Numbers in an Interval Range

🏠 ⬅️ ➡️

Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

Example 1:

Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9].

Constraints:

  • 0 <= low <= high <= 10^9

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    integer :: low, high, count

    ! Example 1
    low = 3
    high = 7
    print '(I0)', countOddNumbers(low, high)

    ! Example 2
    low = 8
    high = 10
    print '(I0)', countOddNumbers(low, high)

contains

    function countOddNumbers(low, high) result(count)
        implicit none
        integer, intent(in) :: low, high
        integer :: i, count

        count = 0
        do i = low, high
            if (mod(i, 2) /= 0) then
                count = count + 1
            end if
        end do
    end function countOddNumbers
end program main
Compiled
Executed
Correct
```
program odd_numbers
    implicit none
    integer :: low, high, i, count

    ! Read the input
    read *, low, high

    ! Initialize the count
    count = 0

    ! Loop through the numbers between low and high
    do i = low, high
        ! If the number is odd, increment the count
        if (mod(i, 2) /= 0) then
            count = count + 1
        end if
    end do

    ! Print the output
    write (*, '(i0)') count
end program odd_numbers
```
🌐 Data from online sources
def count_odds(low, high):
    return (high - low) // 2 + (1 if low % 2 == 1 or high % 2 == 1 else 0)

The algorithm first calculates the total number of integer values between low and high, using the difference divided by 2. Then, it checks whether low or high is odd (remainder when divided by 2 equals 1). If either of them is odd, it means we have one more odd number to include, so we add 1 to the result. Otherwise, we don't add anything, as the range does not include an extra odd number. This algorithm is efficient and will directly provide the count of odd numbers within the range without any looping.

🌐 Data from online sources
int count_odds(int low, int high) {
    return (high - low) / 2 + ((low % 2 == 1 || high % 2 == 1) ? 1 : 0);
}

The algorithm first calculates the total number of integer values between low and high, using the difference divided by 2. Then, it checks whether low or high is odd (remainder when divided by 2 equals 1). If either of them is odd, it means we have one more odd number to include, so we add 1 to the result. Otherwise, we don't add anything, as the range does not include an extra odd number. This algorithm is efficient and will directly provide the count of odd numbers within the range without any looping.