📌  相关文章
📜  通过用它们的 GCD 替换对,将前 N 个自然数的序列修改为给定的数组

📅  最后修改于: 2021-10-26 02:34:51             🧑  作者: Mango

给定一个整数N和阵列ARR []中,任务是检查通过选择任何一对如果第一n个自然数的序列,即{1,2,3,… N}可以由等于给Arr [] i, j)来自序列并用ij的 GCD 替换ij 。如果可能,请打印“是” 。否则,打印“否”

例子:

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

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

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

下面是上述方法的实现:

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


Javascript


输出:
Yes

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