📜  将前N个自然数分成两个具有非互素和的子序列

📅  最后修改于: 2021-05-04 21:26:40             🧑  作者: Mango

给定整数N ( N &e; 3 ),任务是将所有从1N的数分成两个子序列,以使两个子序列的总和互不互质。

例子:

天真的方法:最简单的方法是以所有可能的方式将前N个自然数分成两个子序列,对于每种组合,请检查两个子序列的和是否为非互质数。如果发现任何子序列对都是正确的,则打印该子序列并退出循环。

时间复杂度: O(2 N )
辅助空间: O(1)

高效的方法:基于以下观察,可以对上述方法进行优化:

  • 第一个(N – 1)个自然数的总和由(N *(N – 1))/ 2给出
  • 因此, (((N *(N – 1))/ 2)N的GCD为N。

根据以上观察,将一个子序列中[1,N]范围内的所有数字插入,将N插入另一个子序列中。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to split 1 to N
// into two subsequences
// with non-coprime sums
void printSubsequence(int N)
{
    cout << "{ ";
    for (int i = 1; i < N - 1; i++) {
        cout << i << ", ";
    }
 
    cout << N - 1 << " }\n";
 
    cout << "{ " << N << " }";
}
// Driver Code
int main()
{
    int N = 8;
 
    printSubsequence(N);
 
    return 0;
}


Java
// Java program for the above approach
class GFG
{
   
  // Function to split 1 to N
  // into two subsequences
  // with non-coprime sums
  public static void printSubsequence(int N)
  {
    System.out.print("{ ");
    for (int i = 1; i < N - 1; i++)
    {
      System.out.print(i + ", ");
    }
 
    System.out.println(N - 1 + " }");
    System.out.print("{ " + N + " }");
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 8;
    printSubsequence(N);
  }
}
 
// This code is contributed by divyesh072019


Python3
# Python3 program for the above approach
 
# Function to split 1 to N
# into two subsequences
# with non-coprime sums
def printSubsequence(N):
     
    print("{ ", end = "")
    for i in range(1, N - 1):
        print(i, end = ", ")
 
    print(N - 1, end = " }\n")
 
    print("{", N, "}")
 
# Driver Code
if __name__ == '__main__':
     
    N = 8
 
    printSubsequence(N)
     
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
class GFG
{
   
  // Function to split 1 to N
  // into two subsequences
  // with non-coprime sums
  public static void printSubsequence(int N)
  {
    Console.Write("{ ");
    for (int i = 1; i < N - 1; i++)
    {
        Console.Write(i + ", ");
    }
 
    Console.WriteLine(N - 1 + " }");
    Console.Write("{ " + N + " }");
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int N = 8;
    printSubsequence(N);
  }
}
 
// This code is contributed by AnkThon


输出:
{ 1, 2, 3, 4, 5, 6, 7 }
{ 8 }

时间复杂度: O(N)
辅助空间: O(1)