Given a number N the task is to find the number of pairs containing an even and an odd number from numbers between 1 and N inclusive.
Note: The order of numbers in the pair does not matter. That is (1, 2) and (2, 1) are the same.
Examples:
Input: N = 3 Output: 2 The pairs are (1, 2) and (2, 3).
Input: N = 6 Output: 9 The pairs are (1, 2), (1, 4), (1, 6), (2, 3), (2, 5), (3, 4), (3, 6), (4, 5), (5, 6).
Approach: The number of ways to form the pairs is (Total number of Even numbers*Total number of Odd numbers).
Thus
- if N is an even number of even numbers = number of odd numbers = N/2
- if N is an odd number of even numbers = N/2 and the number of odd numbers = N/2+1
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach#include <iostream>using namespace std;// Driver codeint main(){ int N = 6; int Even = N / 2; int Odd = N - Even; cout << Even * Odd; return 0; // This code is contributed // by ANKITRAI1} |
Java
// Java implementation of the above approachimport java.util.*;import java.lang.*;import java.io.*;class GFG{// Driver codepublic static void main(String args[]){ int N = 6; int Even = N / 2 ; int Odd = N - Even ; System.out.println( Even * Odd ); }} |
Python3
# Python implementation of the above approachN = 6 # number of even numbersEven = N//2# number of odd numbersOdd = N-Even print(Even * Odd) |
C#
// C# implementation of the // above approachusing System;class GFG{// Driver codepublic static void Main(){ int N = 6; int Even = N / 2 ; int Odd = N - Even ; Console.WriteLine(Even * Odd);}}// This code is contributed// by Akanksha Rai(Abby_akku) |
PHP
<?php // PHP implementation of the // above approach // Driver code$N = 6;$Even = $N / 2 ;$Odd = $N - $Even ; echo $Even * $Odd ; // This code is contributed// by ChitraNayal?> |
Javascript
<script>// Javascript implementation of the above approach // Driver code let N = 6; let Even = Math.floor(N / 2) ; let Odd = N - Even ; document.write( Even * Odd ); // This code is contributed by avanitrachhadiya2155</script> |
9
Time Complexity: O(1)
Space Complexity: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
