将一个数分成两个不相等的偶数部分
给定一个正整数N 。任务是决定整数是否可以分成两个不相等的正偶数部分。
例子:
Input: N = 8
Output: YES
Explanation: 8 can be divided into two different even parts i.e. 2 and 6.
Input: N = 5
Output: NO
Explanation: 5 can not be divided into two even parts in any way.
Input: N = 4
Output: NO
Explanation: 4 can be divided into two even parts, 2 and 2. Since the numbers are equal, the output is NO.
先决条件:了解 if-else 条件语句。
方法:问题的核心概念在于以下观察:
The sum of any two even numbers is always even. Conversely any even number can be expressed as sum of two even numbers.
但这里有两个例外
- 数字 2 在这里是个例外。它只能表示为两个奇数的和(1 + 1)。
- 数字 4 只能表示为相等偶数 (2 + 2) 的总和。
因此,只有当N 为偶数且不等于 2 或 4时,才有可能将N表示为两个偶数之和。如果 N 是奇数,则不可能将其分成两个偶数部分。请按照以下步骤操作:
- 检查 N = 2 还是 N = 4。
- 如果是,则打印 NO。
- 否则检查 N 是否为偶数(即 2 的倍数)
- 如果是,则打印 YES。
- 否则,打印 NO。
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
using namespace std;
// Function to check if N can be divided
// into two unequal even parts
bool evenParts(int N)
{
// Check if N is equal to 2 or 4
if(N == 2 || N == 4)
return false;
// Check if N is even
if(N % 2 == 0)
return true;
else
return false;
}
//Driver code
int main(){
int N = 8;
// Function call
bool ans = evenParts(N);
if(ans)
std::cout << "YES" << '\n';
else
std::cout << "NO" << '\n';
return 0;
}
Java
// Java code to implement above approach
import java.util.*;
public class GFG {
// Function to check if N can be divided
// into two unequal even parts
static boolean evenParts(int N)
{
// Check if N is equal to 2 or 4
if(N == 2 || N == 4)
return false;
// Check if N is even
if(N % 2 == 0)
return true;
else
return false;
}
// Driver code
public static void main(String args[])
{
int N = 8;
// Function call
boolean ans = evenParts(N);
if(ans)
System.out.println("YES");
else
System.out.println("NO");
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code for the above approach
# Function to check if N can be divided
# into two unequal even parts
def evenParts(N):
# Check if N is equal to 2 or 4
if (N == 2 or N == 4):
return False
# Check if N is even
if (N % 2 == 0):
return True
else:
return False
# Driver code
N = 8
# Function call
ans = evenParts(N)
if (ans):
print("YES")
else:
print("NO")
# This code is contributed by Saurabh Jaiswal.
C#
// C# code to implement above approach
using System;
class GFG {
// Function to check if N can be divided
// into two unequal even parts
static bool evenParts(int N)
{
// Check if N is equal to 2 or 4
if(N == 2 || N == 4)
return false;
// Check if N is even
if(N % 2 == 0)
return true;
else
return false;
}
// Driver code
public static void Main()
{
int N = 8;
// Function call
bool ans = evenParts(N);
if(ans)
Console.Write("YES" + '\n');
else
Console.Write("NO" + '\n');
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
YES
时间复杂度: O(1)
辅助空间: O(1)