将给定的数字分成两个偶数部分
给定一个数字N ,任务是检查这个数字是否可以分成 2 个偶数部分。
例子:
Input: N = 8
Output: YES
Explanation: 8 can be divided into two even parts in two ways, 2, 6 or 4, 4 as both are even.
Input: N = 5
Output: NO
天真的方法:检查直到N的所有数字对,使得它们都是偶数并且它们的总和都为N 。如果可能,打印 Yes,否则打印 No。
时间复杂度: O(N 2 )
辅助空间: O(1)
有效方法:观察可以看出,任何偶数都可以表示为除2之外的两个偶数之和,并且没有两个偶数相加可以形成奇数。
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
using namespace std;
// Divide number into 2 even parts
bool divNum(int n)
{
return (n <= 2
? false
: (n % 2 == 0
? true
: false));
}
// Driven Program
int main()
{
int n = 8;
cout << (divNum(n) ? "YES" : "NO")
<< endl;
return 0;
}
Java
// Java code to implement above approach
import java.util.*;
public class GFG {
// Divide number into 2 even parts
static boolean divNum(int n)
{
return (n <= 2 ? false
: (n % 2 == 0 ? true : false));
}
// Driven Program
public static void main(String args[])
{
int n = 8;
System.out.println(divNum(n) ? "YES" : "NO");
}
}
// This code is contributed by Samim Hossain Mondal.
Python
# Pyhton program for above approach
# Divide number into 2 even parts
def divNum(n):
ans = False if n <= 2 else True if n % 2 == 0 else False
return ans
# Driver Code
n = 8
if(divNum(n) == True):
print("YES")
else:
print("NO")
# This code is contributed by Samim Hossain Mondal.
C#
// C# code to implement above approach
using System;
class GFG {
// Divide number into 2 even parts
static bool divNum(int n)
{
return (n <= 2 ? false
: (n % 2 == 0 ? true : false));
}
// Driven Program
public static void Main()
{
int n = 8;
Console.WriteLine(divNum(n) ? "YES" : "NO");
}
}
// This code is contributed by ukasp.
Javascript
输出
YES
时间复杂度: O(1)
辅助空间: O(1)