Count pairs from a given range having even sum | C ++ program for the above approach ; Function to find the count of ordered pairs having even sum ; Stores count of even numbers in the range [ L , R ] ; If L is even ; Update count_even ; Update count_odd ; Stores count of odd numbers in the range [ L , R ] ; Update count_odd ; Update count_odd ; Stores count of pairs whose sum is even and both elements of the pairs are also even ; Stores count of pairs whose sum is even and both elements of the pairs are odd ; Print total ordered pairs whose sum is even ; Driver Code ; Given L & R ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int L , int R ) { int count_even ; if ( L % 2 == 0 ) { count_even = ( R / 2 ) - ( L / 2 ) + 1 ; } else { count_even = ( R / 2 ) - ( L / 2 ) ; } int count_odd ; if ( L % 2 == 0 ) { count_odd = ( ( R + 1 ) / 2 ) - ( ( L + 1 ) / 2 ) ; } else { count_odd = ( ( R + 1 ) / 2 ) - ( ( L + 1 ) / 2 ) + 1 ; } count_even *= count_even ; count_odd *= count_odd ; cout << count_even + count_odd ; } int main ( ) { int L = 1 , R = 3 ; countPairs ( L , R ) ; return 0 ; }