📜  选择包含从1到N的偶数和奇数的对的方式的数量

📅  最后修改于: 2021-04-27 22:50:05             🧑  作者: Mango

给定数字N,任务是从1到N之间(含1和N)的数字中查找包含偶数和奇数的对的数量。
注意:对中的数字顺序并不重要,因为(1,2)和(2,1)相同。

例子

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).

方法:形成对的方式数为(偶数总数*奇数总数)

因此

  1. 如果N是偶数个偶数=奇数个数= N / 2
  2. 如果N是偶数的奇数= N / 2并且奇数的数量= N / 2 + 1

下面是上述方法的实现:

C++
// C++ implementation of the above approach 
#include 
using namespace std;
  
// Driver code
int 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 approach
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
  
// Driver code
public 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 approach
N = 6
  
 # number of even numbers
Even = N//2
  
# number of odd numbers
Odd = N-Even 
print(Even * Odd)


C#
// C# implementation of the 
// above approach
using System;
  
class GFG
{
  
// Driver code
public 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


输出:
9