Simplest way to calculate amount of even numbers in given range

前端 未结 16 2398
小蘑菇
小蘑菇 2021-02-13 14:10

What is the simplest way to calculate the amount of even numbers in a range of unsigned integers?

An example: if range is [0...4] then the answer is 3 (0,2,4)

I\

相关标签:
16条回答
  • 2021-02-13 14:46

    Oh well, why not:

    #include <cassert>
    
    int ecount( int begin, int end ) {
        assert( begin <= end );
        int size = (end - begin) + 1;
        if ( size % 2 == 0  || begin % 2 == 1 ) {
            return size / 2;
        }
        else {
            return size / 2 + 1;
        }
    }
    
    int main() {
        assert( ecount( 1, 5 ) == 2 );
        assert( ecount( 1, 6 ) == 3 );
        assert( ecount( 2, 6 ) == 3 );
        assert( ecount( 1, 1 ) == 0 );
        assert( ecount( 2, 2 ) == 1 );
    }
    
    0 讨论(0)
  • 2021-02-13 14:50
    int start, stop;
    start = 0;
    stop = 9;
    printf("%d",(stop-start)/2+((!(start%2) || !(stop%2)) ? 1 : 0));
    

    Where start and stop can hold any value. No need to iterate to to determine this number.

    0 讨论(0)
  • 2021-02-13 14:53

    This'll do the trick, even for ranges with negative numbers.

    int even = (last - first + 2 - Math.abs(first % 2) - Math.abs(last % 2)) / 2;
    

    Tested with the following code:

    public static void main(String[] args) {
        int[][] numbers = {{0, 4}, {0, 5}, {1, 4}, {1, 5}, {4, 4}, {5, 5},
                           {-1, 0}, {-5, 0}, {-4, 5}, {-5, 5}, {-4, -4}, {-5, -5}};
    
        for (int[] pair : numbers) {
            int first = pair[0];
            int last = pair[1];
            int even = (last - first + 2 - Math.abs(first % 2) - Math.abs(last % 2)) / 2;
            System.out.println("[" + first + ", " + last + "] -> " + even);
        }
    }
    

    Output:

    [0, 4] -> 3
    [0, 5] -> 3
    [1, 4] -> 2
    [1, 5] -> 2
    [4, 4] -> 1
    [5, 5] -> 0
    [-1, 0] -> 1
    [-5, 0] -> 3
    [-4, 5] -> 5
    [-5, 5] -> 5
    [-4, -4] -> 1
    [-5, -5] -> 0
    
    0 讨论(0)
  • 2021-02-13 14:53

    This does not require any conditions at all:

    evencount = floor((max - min)/2) + 1
    
    0 讨论(0)
  • 2021-02-13 14:57

    I'd say

    (max - min + 1 + (min % 2)) / 2
    

    Edit: Erm okay for some reason I thought that (min % 2) returns 1 for even numbers.... :). The correct version is

    (max - min + 1 + 1 - (min % 2)) / 2
    

    or rather

    (max - min + 2 - (min % 2)) / 2
    
    0 讨论(0)
  • 2021-02-13 14:58

    The first even number in the range is: (begin + 1) & ~1 (round begin up to even number).

    The last even number in the range is: end & ~1 (round end down to even number).

    The total number of even numbers in the range is therefore: (end & ~1) - ((begin + 1) & ~1) + 1.

    int num_evens = (end & ~1) - ((begin + 1) & ~1) + 1;
    
    0 讨论(0)
提交回复
热议问题