Open In App

Modify sequence of first N natural numbers to a given array by replacing pairs with their GCD

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N and an array arr[], the task is to check if a sequence of first N natural numbers, i.e. {1, 2, 3, .. N} can be made equal to arr[] by choosing any pair (i, j) from the sequence and replacing both i and j by GCD of i and j. If possible, then print “Yes”. Otherwise, print “No”.

Examples:

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

Approach:

We can start by iterating over all pairs of numbers (i, j) such that 1 ? i < j ? N and finding their GCD using the Euclidean algorithm. Then, if we find a pair (i, j) such that GCD(i, j) is equal to arr[i-1] and arr[j-1], we can replace both i and j with GCD(i, j) and continue with the modified sequence. If we are able to modify the sequence to be equal to arr[], then we can print “Yes”. Otherwise, we can print “No”.

Algorithm:

  • Initialize a sequence of first N natural numbers, i.e. {1, 2, 3, .. N}.
  • Iterate over all pairs of numbers (i, j) such that 1 ? i < j ? N.
  • Compute the GCD of i and j using the Euclidean algorithm.
  • If GCD(i, j) is equal to arr[i-1] and arr[j-1], replace both i and j with GCD(i, j) in the sequence.
  • If the modified sequence is equal to arr[], print “Yes” and return.
  • If no such pair (i, j) is found, print “No” and return.

Implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to compute the GCD using the Euclidean algorithm
int gcd(int a, int b) {
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to check if a sequence of first N natural numbers can be made equal to arr[]
void checkSequence(int N, int arr[]) {
    // Initialize the sequence of first N natural numbers
    vector<int> seq(N);
    for (int i = 0; i < N; i++)
        seq[i] = i+1;
 
    // Iterate over all pairs of numbers (i, j) such that 1 ? i < j ? N
    for (int i = 0; i < N; i++) {
        for (int j = i+1; j < N; j++) {
            // Compute the GCD of i and j
            int g = gcd(seq[i], seq[j]);
            // If GCD(i, j) is equal to arr[i-1] and arr[j-1], replace both i and j with GCD(i, j) in the sequence
            if (g == arr[i] && g == arr[j]) {
                seq[i] = seq[j] = g;
                break;
            }
        }
        // If the modified sequence is equal to arr[], print "Yes" and return
        if (seq == vector<int>(arr, arr+N)) {
            cout << "Yes\n";
            return;
        }
    }
    // If no such pair (i, j) is found, print "No" and return
    cout << "No\n";
}
 
// Driver code
int main() {
    int N = 4;
    int arr[] = {1, 2, 3, 2};
    checkSequence(N, arr);
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
    // Function to compute the GCD using the Euclidean
    // algorithm
    public static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }
 
    // Function to check if a sequence of first N natural
    // numbers can be made equal to arr[]
    public static void checkSequence(int N, int[] arr)
    {
        // Initialize the sequence of first N natural
        // numbers
        List<Integer> seq = new ArrayList<>();
        for (int i = 0; i < N; i++)
            seq.add(i + 1);
 
        // Iterate over all pairs of numbers (i, j) such
        // that 1 ? i < j ? N
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                // Compute the GCD of i and j
                int g = gcd(seq.get(i), seq.get(j));
                // If GCD(i, j) is equal to arr[i-1] and
                // arr[j-1], replace both i and j with
                // GCD(i, j) in the sequence
                if (g == arr[i] && g == arr[j]) {
                    seq.set(i, g);
                    seq.set(j, g);
                    break;
                }
            }
            // If the modified sequence is equal to arr[],
            // print "Yes" and return
            if (seq.equals(Arrays.asList(
                    Arrays.stream(arr).boxed().toArray(
                        Integer[] ::new)))) {
                System.out.println("Yes");
                return;
            }
        }
        // If no such pair (i, j) is found, print "No" and
        // return
        System.out.println("No");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 4;
        int[] arr = { 1, 2, 3, 2 };
        checkSequence(N, arr);
    }
}
// Contributed by sdeadityasharma


Python3




from typing import List
import math
 
# Function to compute the GCD using the Euclidean algorithm
def gcd(a: int, b: int) -> int:
    if a == 0:
        return b
    return gcd(b % a, a)
 
# Function to check if a sequence of first N natural
# numbers can be made equal to arr[]
def checkSequence(N: int, arr: List[int]):
    # Initialize the sequence of first N natural numbers
    seq = list(range(1, N+1))
 
    # Iterate over all pairs of numbers (i, j) such that 1 ? i < j ? N
    for i in range(N):
        for j in range(i+1, N):
            # Compute the GCD of i and j
            g = gcd(seq[i], seq[j])
            # If GCD(i, j) is equal to arr[i-1] and arr[j-1], replace both i and j with
            # GCD(i, j) in the sequence
            if g == arr[i] and g == arr[j]:
                seq[i] = g
                seq[j] = g
                break
        # If the modified sequence is equal to arr[], print "Yes" and return
        if seq == list(range(1, N+1)):
            print("Yes")
            return
    # If no such pair (i, j) is found, print "No" and return
    print("No")
 
# Driver code
if __name__ == '__main__':
    N = 4
    arr = [1, 2, 3, 2]
    checkSequence(N, arr)


C#




// C# Program for the above approach
 
using System;
using System.Collections.Generic;
using System.Linq;
 
class MainClass {
    // Function to compute the GCD using the Euclidean
    // algorithm
    public static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }
 
    // Function to check if a sequence of first N natural
    // numbers can be made equal to arr[]
    public static void checkSequence(int N, int[] arr)
    {
        // Initialize the sequence of first N natural
        // numbers
        List<int> seq = new List<int>();
        for (int i = 0; i < N; i++)
            seq.Add(i + 1);
 
        // Iterate over all pairs of numbers (i, j) such
        // that 1 ? i < j ? N
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                // Compute the GCD of i and j
                int g = gcd(seq[i], seq[j]);
                // If GCD(i, j) is equal to arr[i-1] and
                // arr[j-1], replace both i and j with
                // GCD(i, j) in the sequence
                if (g == arr[i] && g == arr[j]) {
                    seq[i] = g;
                    seq[j] = g;
                    break;
                }
            }
            // If the modified sequence is equal to arr[],
            // print "Yes" and return
            if (seq.SequenceEqual(arr)) {
                Console.WriteLine("Yes");
                return;
            }
        }
        // If no such pair (i, j) is found, print "No" and
        // return
        Console.WriteLine("No");
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int N = 4;
        int[] arr = { 1, 2, 3, 2 };
        checkSequence(N, arr);
    }
}
 
// This code is contributed by Prince Kumar


Javascript




// Function to compute the GCD using the Euclidean algorithm
function gcd(a, b) {
    if (a === 0) {
        return b;
    }
    return gcd(b % a, a);
}
 
// Function to check if a sequence of first N natural
// numbers can be made equal to arr[]
function checkSequence(N, arr) {
    // Initialize the sequence of first N natural numbers
    const seq = Array.from({ length: N }, (_, i) => i + 1);
 
    // Iterate over all pairs of numbers (i, j) such that 1 ? i < j ? N
    for (let i = 0; i < N; i++) {
        for (let j = i + 1; j < N; j++) {
            // Compute the GCD of i and j
            const g = gcd(seq[i], seq[j]);
            // If GCD(i, j) is equal to arr[i-1] and arr[j-1], replace both i and j with
            // GCD(i, j) in the sequence
            if (g === arr[i] && g === arr[j]) {
                seq[i] = g;
                seq[j] = g;
                break;
            }
        }
        // If the modified sequence is equal to arr[], print "Yes" and return
        if (seq.every((value, index) => value === index + 1)) {
            console.log("Yes");
            return;
        }
    }
    // If no such pair (i, j) is found, print "No" and return
    console.log("No");
}
 
// Driver code
const N = 4;
const arr = [1, 2, 3, 2];
checkSequence(N, arr);


Output

Yes

Time Complexity: O(N * sqrt(N) * log(N))

Space Complexity: O(N)

Approach: The idea is based on the fact that the GCD of two numbers lies between 1 and the minimum of the two numbers. By definition of gcd, it’s the greatest number that divides both. Therefore, make the number at an index smaller if and only if there exists some number which is its factor. Hence, it can be concluded that for every ith index in the array, if the follow condition holds true, the array arr[] can be obtained from the sequence of first N natural numbers.

(i + 1) % arr[i] == 0

Follow the steps below to solve the problem: 

  • Traverse the array arr[] using variable i.
  • For every ith index, check if (i + 1) % arr[i] is equal to 0 or not. If found to be false for any array element, print “No”.
  • Otherwise, after complete traversal of the array, print “Yes”.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if array arr[]
// can be obtained from first N
// natural numbers or not
void isSequenceValid(vector<int>& 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<int> 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




<script>
// Javascript program to implement
// the above approach
 
// Function to check if array arr[]
// can be obtained from first N
// natural numbers or not
function isSequenceValid(B, N)
{
    for(let i = 0; i < N; i++)
    {
        if ((i + 1) % B[i] != 0)
        {
            document.write("No");
            return;
        }
    }
    document.write("Yes");
}
 
// Driver code
 
    let N = 4;
    let arr = [ 1, 2, 3, 2 ];
      
    // Function Call
    isSequenceValid(arr, N);
     
    // This code is contributed by souravghosh0416.
</script>


Output: 

Yes

 

Time Complexity: O(N)
Auxiliary Space: O(1)



Similar Reads

Modify a given array by replacing each element with the sum or product of their digits based on a given condition
Given an array arr[] consisting of N integers, the task is to modify the array elements after performing only one of the following operations on each array elements: If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all the digits of that element.Otherwise, update that el
8 min read
Check if GCD of Array can be made greater than 1 by replacing pairs with their products
Given three integers L, R, and K. Consider an array arr[] consisting of all the elements from L to R, the task is to check whether the GCD of the array can be made greater than 1 using at most K operations. An operation is defined below: Choose any two numbers from the arrayRemove them from the arrayInsert their product back into the array Examples
7 min read
Modify string by replacing all occurrences of given characters by specified replacing characters
Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[][2], the task is to modify the given string S by replacing all occurrences of character P[i][0] with character P[i][1]. Examples: Input: S = "aabbgg", P[][2] = {{a, b}, {b, g}, {g, a}}Output: bbggaaExplanation:Replace 'a' by 'b' in the original string. Now t
12 min read
Modify array by replacing elements with their farthest co-prime number from a given range
Given an array arr[] consisting of N integers and two positive integers L and R, the task is to find the farthest co-prime number in the range [L, R] for every array element. Examples: Input: arr[] = {5, 150, 120}, L = 2, R = 250Output: 249 7 247Explanation:The number which is co-prime with arr[0] and farthest from it is 249.The number which is co-
7 min read
Modify array by replacing each element with nearest power of GCD of all previous elements
Given an array arr[] consisting of N positive integers, the task is to replace each array element with the nearest power of GCD of all the preceding array elements. If there exists more than one possible answer, then print any one of them. Examples: Input: arr[] = {4, 2, 8, 2}Output: 4 1 8 2Explanation: For element arr[0], the element remains the s
9 min read
Check if GCD of [L, R] can be made &gt;1 by replacing pairs with their product at most K times
Given a range [L, R] and an integer K, the task is to check if it is possible to make the GCD of all integers in the given range more than 1 using at most K operations wherein each operation replace any two integers in the range with their product. Examples: Input: L = 1, R = 5, K = 3 .Output: YesExplanation: All the integers in the given range are
5 min read
Generate a sequence from first X natural numbers which adds up to S on raising 2 to the power of their lowest set bits
Given two integers X and S, the task is to construct a sequence of distinct integers from the range [1, X] such that the sum of value 2K is equal to S, where K is the position of the first set bit from the end ( 0-based indexing )of the binary representation of each element is S. Examples: Input: X = 3, S = 4Output: 2 3 1Explanation:Summation of 2K
10 min read
Maximize count of equal numbers in Array of numbers upto N by replacing pairs with their sum
Given an array arr[] containing natural numbers from 1 to N, the task is to find the maximum number of elements that can be made equal after the below operations: Remove any pair of elements from the array and insert their sum to an array.Repeat the above operation any numbers of times to maximize the count of equal elements. Examples: Input: arr[]
3 min read
Maximum GCD among all pairs (i, j) of first N natural numbers
Given a positive integer N &gt; 1, the task is to find the maximum GCD among all the pairs (i, j) such that i &lt; j &lt; N.Examples: Input: N = 3Output: 3Explanation:All the possible pairs are: (1, 2) (1, 3) (2, 3) with GCD 1.Input: N = 4Output: 2Explanation:Out of all the possible pairs the pair with max GCD is (2, 4) with a value 2. Naive Approa
6 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read