Count Even Odd In a Given Range

Count Even Odd In a Given Range

Sometimes we need to find the number of Even and Odd Counts in a given range. So, how can we do it?

Bruthforces -

we write down all the numbers to our given range. And then count even and odd. But this is not a good idea. Cause it takes too many times to count even and odd from a range. So what to do :p

Using Maths -

Give the rang a and b. So how many numbers are there? The answer is N = (b-a)+1. So The approach is :

         1. if N is even then the even and odd count is simply N/2.
         2. But if the N is Odd then -
                 * if a or b is odd Then Odd Count is N/2+1 and the Even Count is N-(Odd Count).
                 * else , Odd Count is N/2 and the Even Count is N-(Odd Count).

Let's Coded The idea:

#include <bits/stdc++.h>

using namespace std;
int countOdd(int a, int b){
    int N = (b - a) / 2;
    if (a % 2 != 0 || b % 2 != 0)
        N += 1;

    return N;
}

int main()
{   
    freopen("int.txt", "r", stdin);
    int a, b; cin>>a>>b;
    int odds = countOdd(a, b);
    int evens = (b - a + 1) - odds;

    cout << "Count of odd numbers is " << odds << endl;
    cout << "Count of even numbers is " << evens << endl;

    return 0;
}