📜  将前 N 个自然数拆分为两个非互质和的子序列

📅  最后修改于: 2021-10-26 06:22:22             🧑  作者: 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


Javascript


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

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