给定一个整数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}和{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)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。