给定一个数字 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).
方法:形成对的方法的数量是(偶数总数*奇数总数) 。
因此
- 如果 N 是偶数的偶数 = 奇数 = N/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
Javascript
输出:
9
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。