📜  通过将对的前N个自然数的序列替换为GCD来修改给定数组的序列

📅  最后修改于: 2021-05-06 07:44:47             🧑  作者: Mango

给定一个整数N和一个数组arr [] ,任务是检查是否可以通过选择任意对使前N个自然数(即{1、2、3,.. N})的序列与arr []相等( i,j)从序列开始,并用ij的GCD替换ij 。如果可能,请打印“是” 。否则,打印“否”

例子:

方法:这个想法基于以下事实:两个数字的GCD介于1和两个数字的最小值之间。根据gcd的定义,这是将两者相除的最大数。因此,仅当存在某个数字作为其因子时,才使索引处的数字更小。因此,可以得出结论,对于数组中的每个i索引,如果遵循条件成立,则可以从前N个自然数的序列中获得数组arr []

请按照以下步骤解决问题:

  • 使用变量i遍历数组arr []
  • 对于每个i索引,检查( i + 1)%arr [i]是否等于0 。如果发现任何数组元素为假,则打印“ No”
  • 否则,在遍历数组后,打印“是”

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if array arr[]
// can be obtained from first N
// natural numbers or not
void isSequenceValid(vector& B,
                     int N)
{
    for (int i = 0; i < N; i++) {
 
        if ((i + 1) % B[i] != 0) {
            cout << "No";
            return;
        }
    }
 
    cout << "Yes";
}
 
// Driver Code
int main()
{
    int N = 4;
    vector arr{ 1, 2, 3, 2 };
 
    // Function Call
    isSequenceValid(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
      
// Function to check if array arr[]
// can be obtained from first N
// natural numbers or not
static void isSequenceValid(int[] B,
                            int N)
{
    for(int i = 0; i < N; i++)
    {
        if ((i + 1) % B[i] != 0)
        {
            System.out.print("No");
            return;
        }
    }
    System.out.print("Yes");
}
  
// Driver code
public static void main(String[] args)
{
    int N = 4;
    int[] arr = { 1, 2, 3, 2 };
     
    // Function Call
    isSequenceValid(arr, N);
}
}
  
// This code is contributed by sanjoy_62


Python3
# Python3 program for the above approach
 
# Function to check if array arr[]
# can be obtained from first N
# natural numbers or not
def isSequenceValid(B, N):
     
    for i in range(N):
        if ((i + 1) % B[i] != 0):
            print("No")
            return
         
    print("Yes")
     
# Driver Code
N = 4
arr = [ 1, 2, 3, 2 ]
  
# Function Call
isSequenceValid(arr, N)
 
# This code is contributed by susmitakundugoaldanga


C#
// C# program for the above approach
using System;
 
class GFG{
       
// Function to check if array arr[]
// can be obtained from first N
// natural numbers or not
static void isSequenceValid(int[] B,
                            int N)
{
    for(int i = 0; i < N; i++)
    {
        if ((i + 1) % B[i] != 0)
        {
            Console.WriteLine("No");
            return;
        }
    }
    Console.WriteLine("Yes");
}
   
// Driver code
public static void Main()
{
    int N = 4;
    int[] arr = { 1, 2, 3, 2 };
      
    // Function Call
    isSequenceValid(arr, N);
}
}
 
// This code is contributed by code_hunt


输出:
Yes

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