给定一个整数N ,任务是将前N个自然数划分为两个非空集合,以使这些集合的总和互不互质。如果可能,则找到可能的分区,然后打印-1,否则打印两个集合的元素之和。
例子:
Input: N = 5
Output: 10 5
{1, 2, 3, 4} and {5} are the valid partitions.
Input: N = 2
Output: -1
方法:
- 如果N≤2,则将-1打印为-1,因为唯一可能的分区是{1}和{2} ,其中两组的总和互为互质。
- 现在,如果N为奇数,则我们将N放在一组中,并将第一个(N – 1)个数字放入其他组中。因此,这两个集合的总和将为N和N *(N – 1)/ 2,并且由于它们的gcd为N ,因此它们不会互质。
- 如果N是偶数,那么我们做与前一个相同的事,两组的总和将为N和N *(N – 1)/ 2 。由于N是偶数,所以(N – 1)不能被2整除,但是N是可整除的,其总和为(N / 2)*(N – 1) ,其gcd将为N / 2 。由于N / 2是N的因数,所以它们不互质到彼此。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the required sets
void find_set(int n)
{
// Impossible case
if (n <= 2) {
cout << "-1";
return;
}
// Sum of first n-1 natural numbers
int sum1 = (n * (n - 1)) / 2;
int sum2 = n;
cout << sum1 << " " << sum2;
}
// Driver code
int main()
{
int n = 8;
find_set(n);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Function to find the required sets
static void find_set(int n)
{
// Impossible case
if (n <= 2)
{
System.out.println ("-1");
return;
}
// Sum of first n-1 natural numbers
int sum1 = (n * (n - 1)) / 2;
int sum2 = n;
System.out.println (sum1 + " " +sum2 );
}
// Driver code
public static void main (String[] args)
{
int n = 8;
find_set(n);
}
}
// This code is contributed by jit_t.
Python3
# Python implementation of the approach
# Function to find the required sets
def find_set(n):
# Impossible case
if (n <= 2):
print("-1");
return;
# Sum of first n-1 natural numbers
sum1 = (n * (n - 1)) / 2;
sum2 = n;
print(sum1, " ", sum2);
# Driver code
n = 8;
find_set(n);
# This code is contributed by PrinciRaj1992
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find the required sets
static void find_set(int n)
{
// Impossible case
if (n <= 2)
{
Console.WriteLine("-1");
return;
}
// Sum of first n-1 natural numbers
int sum1 = (n * (n - 1)) / 2;
int sum2 = n;
Console.WriteLine(sum1 + " " +sum2 );
}
// Driver code
public static void Main ()
{
int n = 8;
find_set(n);
}
}
// This code is contributed by anuj_67...
Javascript
输出:
28 8
时间复杂度: O(1)