给定一个整数N和一个数组arr [] ,任务是检查是否可以通过选择任意对使前N个自然数(即{1、2、3,.. N})的序列与arr []相等( i,j)从序列开始,并用i和j的GCD替换i和j 。如果可能,请打印“是” 。否则,打印“否” 。
例子:
Input: N = 4, arr[] = {1, 2, 3, 2}
Output: Yes
Explanation: For the pair (2, 4) in the sequence {1, 2, 3, 4}, GCD(2, 4) = 2. Now, the sequence modifies to {1, 2, 3, 2}, which is same as arr[].
Input: N = 3, arr[] = {1, 2, 2}
Output: No
方法:这个想法基于以下事实:两个数字的GCD介于1和两个数字的最小值之间。根据gcd的定义,这是将两者相除的最大数。因此,仅当存在某个数字作为其因子时,才使索引处的数字更小。因此,可以得出结论,对于数组中的每个第i个索引,如果遵循条件成立,则可以从前N个自然数的序列中获得数组arr [] 。
(i + 1) % arr[i] == 0
请按照以下步骤解决问题:
- 使用变量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)