给定一个始终是偶数的整数 N ,我们的任务是按照给定的条件打印N 个不同的数字:
- 前半数为偶数,后半数为奇数
- 前半数元素之和与后半数元素之和应相等
如果上述条件满足,则打印数组,否则输出“-1”。
例子:
Input: N = 4
Output: 2 4 1 5
Explanation:
Given number 4 we are required to print 4 numbers. First Half = 2, 4 and their sum is 6, other half = 1, 5 and their sum is also 6.
Input: N = 22
Output: -1
Explanation:
It is not possible to print the required array.
方法:
为了解决上面提到的问题,我们必须观察到整数 N 必须是 4 的倍数。
- 我们知道前 N/2 个偶数的和是偶数,所以如果其他 N/2 个整数的和也是偶数,那么 N/2 一定是偶数,因为奇数个奇数的和是总是奇怪。
- 如果 N/2 是偶数,那么 N 是 4 的倍数,所以如果 n 不能被 4 整除,那么答案是“-1”,否则,就会有一个可能的数组。
- 为了打印数组,我们将考虑两部分,即 N/2 个元素的前半部分将是 2 的倍数,另一半将是 2 – 1 的倍数。对于数组中的最后一个元素,我们将计算通过应用直接公式 N + N / 2 – 1 来计算整数,因为我们应该使两半的和相等。
下面是上述方法的实现:
C++
// C++ implementation to Print N distinct numbers
#include
using namespace std;
// Function to print the required array
bool printArr(int n)
{
// Check if number is a multiple of 4
if (n % 4 == 0) {
// Printing Left Half of the array
for (int i = 1; i <= n / 2; i++)
cout << i * 2 << ' ';
// Printing Right Half of the array
for (int i = 1; i < n / 2; i++)
cout << i * 2 - 1 << ' ';
cout << n + n / 2 - 1 << '\n';
}
else
cout << "-1";
}
// Driver code
int main()
{
int n = 22;
printArr(n);
return 0;
}
Java
// Java implementation to print N distinct numbers
import java.util.*;
class GFG{
// Function to print the required array
static void printArr(int n)
{
// Check if number is a multiple of 4
if(n % 4 == 0)
{
// Printing left half of the array
for(int i = 1; i <= n / 2; i++)
System.out.print(i * 2 + " ");
// Printing Right Half of the array
for(int i = 1; i < n / 2; i++)
System.out.print(i * 2 - 1 + " ");
System.out.println(n + n / 2 - 1);
}
else
System.out.print("-1");
}
// Driver code
public static void main(String[] args)
{
int n = 22;
printArr(n);
}
}
// This code is contributed by amal kumar choubey
Python3
# Python3 implementation to print
# N distinct numbers
# Function to print the required array
def printArr(n):
# Check if number is a multiple of 4
if (n % 4 == 0):
# Printing Left Half of the array
for i in range(1, (n / 2) + 1):
print (i * 2, end = " ")
# Printing Right Half of the array
for i in range(1, n / 2):
print (i * 2 - 1, end = " ")
print (n + n / 2 - 1, end = "\n")
else:
print ("-1")
# Driver code
n = 22
printArr(n)
# This code is contributed by PratikBasu
C#
// C# implementation to print N distinct numbers
using System;
public class GFG{
// Function to print the required array
static void printArr(int n)
{
// Check if number is a multiple of 4
if(n % 4 == 0)
{
// Printing left half of the array
for(int i = 1; i <= n / 2; i++)
Console.Write(i * 2 + " ");
// Printing Right Half of the array
for(int i = 1; i < n / 2; i++)
Console.Write(i * 2 - 1 + " ");
Console.WriteLine(n + n / 2 - 1);
}
else
Console.Write("-1");
}
// Driver code
public static void Main(String[] args)
{
int n = 22;
printArr(n);
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
-1
时间复杂度: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live