Generate an N-length array A[] from an array arr[] such that arr[i] is the last index consisting of a multiple of A[i]
Last Updated :
25 Mar, 2022
Given an array arr[] of length N, with values less than N, the task is to construct another array A[] of same length such that for every ith element in the array A[], arr[i] is the last index (1-based indexing) consisting of a multiple of A[i].
Examples:
Input: arr[] = {4, 1, 2, 3, 4}
Output: 2 3 5 7 2
Explanation:
A[0]: Last index which can contain a multiple of A[0] has to be A[arr[0]] = A[4].
A[1]: Last index which can contain a multiple of A[1] has to be A[arr[1]] = A[1].
A[2]: Last index which can contain a multiple of A[2] has to be A[arr[2]] = A[2].
A[3]: Last index which can contain a multiple of A[3] has to be A[arr[3]] = A[3].
A[4]: Last index which can contain a multiple of A[4] has to be A[arr[4]] = A[4].
Hence, in the final array, A[4] must be divisible by A[0] and A[1], A[2] and A[3] must not be divisible by any other array elements.
Hence, the array A[] = {2, 3, 5, 7, 2} satisfies the condition.
Input: arr[] = {0, 1, 2, 3, 4}
Output: 2 3 5 7 11
Approach: The idea is to place prime numbers as array elements in required indices satisfying the conditions. Follow the steps below to solve the problem:
- Generate all Prime Numbers using Sieve Of Eratosthenes and store it in another array.
- Initialize array A[] with {0}, to store the required array.
- Traverse the array arr[] and perform the following steps:
- Check if A[arr[i]] is non-zero but A[i] is 0. If found to be true, then assign A[i] = A[arr[i]].
- Check if A[arr[i]] and A[i] are both 0 or not. If found to be true, then assign a prime number different to already assigned array elements, to both indices arr[i] and i.
- After completing the above steps, print the elements of array A[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
int sieve[1000000];
// Function to generate all
// prime numbers upto 10^6
void sieveOfPrimes()
{
// Initialize sieve[] as 1
memset(sieve, 1, sizeof(sieve));
int N = 1000000;
// Iterate over the range [2, N]
for (int i = 2; i * i <= N; i++) {
// If current element is non-prime
if (sieve[i] == 0)
continue;
// Make all multiples of i as 0
for (int j = i * i; j <= N; j += i)
sieve[j] = 0;
}
}
// Function to construct an array A[]
// satisfying the given conditions
void getArray(int* arr, int N)
{
// Stores the resultant array
int A[N] = { 0 };
// Stores all prime numbers
vector<int> v;
// Sieve of Eratosthenes
sieveOfPrimes();
for (int i = 2; i <= 1e5; i++)
// Append the integer i
// if it is a prime
if (sieve[i])
v.push_back(i);
// Indicates current position
// in list of prime numbers
int j = 0;
// Traverse the array arr[]
for (int i = 0; i < N; i++) {
int ind = arr[i];
// If already filled with
// another prime number
if (A[i] != 0)
continue;
// If A[i] is not filled
// but A[ind] is filled
else if (A[ind] != 0)
// Store A[i] = A[ind]
A[i] = A[ind];
// If none of them were filled
else {
// To make sure A[i] does
// not affect other values,
// store next prime number
int prime = v[j++];
A[i] = prime;
A[ind] = A[i];
}
}
// Print the resultant array
for (int i = 0; i < N; i++) {
cout << A[i] << " ";
}
}
// Driver Code
int main()
{
int arr[] = { 4, 1, 2, 3, 4 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
getArray(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
static int[] sieve = new int[10000000];
// Function to generate all
// prime numbers upto 10^6
static void sieveOfPrimes()
{
// Initialize sieve[] as 1
Arrays.fill(sieve, 1);
int N = 1000000;
// Iterate over the range [2, N]
for (int i = 2; i * i <= N; i++)
{
// If current element is non-prime
if (sieve[i] == 0)
continue;
// Make all multiples of i as 0
for (int j = i * i; j <= N; j += i)
sieve[j] = 0;
}
}
// Function to construct an array A[]
// satisfying the given conditions
static void getArray(int[] arr, int N)
{
// Stores the resultant array
int A[] = new int[N];
Arrays.fill(A, 0);
// Stores all prime numbers
ArrayList<Integer> v
= new ArrayList<Integer>();
// Sieve of Eratosthenes
sieveOfPrimes();
for (int i = 2; i <= 1000000; i++)
// Append the integer i
// if it is a prime
if (sieve[i] != 0)
v.add(i);
// Indicates current position
// in list of prime numbers
int j = 0;
// Traverse the array arr[]
for (int i = 0; i < N; i++)
{
int ind = arr[i];
// If already filled with
// another prime number
if (A[i] != 0)
continue;
// If A[i] is not filled
// but A[ind] is filled
else if (A[ind] != 0)
// Store A[i] = A[ind]
A[i] = A[ind];
// If none of them were filled
else {
// To make sure A[i] does
// not affect other values,
// store next prime number
int prime = v.get(j++);
A[i] = prime;
A[ind] = A[i];
}
}
// Print the resultant array
for (int i = 0; i < N; i++) {
System.out.print( A[i] + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 4, 1, 2, 3, 4 };
int N = arr.length;
// Function Call
getArray(arr, N);
}
}
// This code is contributed by code_hunt.
Python3
# Python3 program for the above approach
sieve = [1]*(1000000+1)
# Function to generate all
# prime numbers upto 10^6
def sieveOfPrimes():
global sieve
N = 1000000
# Iterate over the range [2, N]
for i in range(2, N + 1):
if i * i > N:
break
# If current element is non-prime
if (sieve[i] == 0):
continue
# Make all multiples of i as 0
for j in range(i * i, N + 1, i):
sieve[j] = 0
# Function to construct an array A[]
# satisfying the given conditions
def getArray(arr, N):
global sieve
# Stores the resultant array
A = [0]*N
# Stores all prime numbers
v = []
# Sieve of Eratosthenes
sieveOfPrimes()
for i in range(2,int(1e5)+1):
# Append the integer i
# if it is a prime
if (sieve[i]):
v.append(i)
# Indicates current position
# in list of prime numbers
j = 0
# Traverse the array arr[]
for i in range(N):
ind = arr[i]
# If already filled with
# another prime number
if (A[i] != 0):
continue
# If A[i] is not filled
# but A[ind] is filled
elif (A[ind] != 0):
# Store A[i] = A[ind]
A[i] = A[ind]
# If none of them were filled
else:
# To make sure A[i] does
# not affect other values,
# store next prime number
prime = v[j]
A[i] = prime
A[ind] = A[i]
j += 1
# Print the resultant array
for i in range(N):
print(A[i], end = " ")
# Driver Code
if __name__ == '__main__':
arr = [4, 1, 2, 3, 4]
N = len(arr)
# Function Call
getArray(arr, N)
# This code is contributed by mohit kumar 29.
C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
static int[] sieve = new int[10000000];
// Function to generate all
// prime numbers upto 10^6
static void sieveOfPrimes()
{
// Initialize sieve[] as 1
for(int i = 0; i < 10000000; i++)
{
sieve[i] = 1;
}
int N = 1000000;
// Iterate over the range [2, N]
for (int i = 2; i * i <= N; i++)
{
// If current element is non-prime
if (sieve[i] == 0)
continue;
// Make all multiples of i as 0
for (int j = i * i; j <= N; j += i)
sieve[j] = 0;
}
}
// Function to construct an array A[]
// satisfying the given conditions
static void getArray(int[] arr, int N)
{
// Stores the resultant array
int[] A = new int[N];
for(int i = 0; i < N; i++)
{
A[i] = 0;
}
// Stores all prime numbers
List<int> v
= new List<int>();
// Sieve of Eratosthenes
sieveOfPrimes();
for (int i = 2; i <= 1000000; i++)
// Append the integer i
// if it is a prime
if (sieve[i] != 0)
v.Add(i);
// Indicates current position
// in list of prime numbers
int j = 0;
// Traverse the array arr[]
for (int i = 0; i < N; i++)
{
int ind = arr[i];
// If already filled with
// another prime number
if (A[i] != 0)
continue;
// If A[i] is not filled
// but A[ind] is filled
else if (A[ind] != 0)
// Store A[i] = A[ind]
A[i] = A[ind];
// If none of them were filled
else {
// To make sure A[i] does
// not affect other values,
// store next prime number
int prime = v[j++];
A[i] = prime;
A[ind] = A[i];
}
}
// Print the resultant array
for (int i = 0; i < N; i++)
{
Console.Write( A[i] + " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 4, 1, 2, 3, 4 };
int N = arr.Length;
// Function Call
getArray(arr, N);
}
}
// This code is contributed by splevel62.
JavaScript
<script>
// JavaScript program for the above approach
var sieve = Array(1000000);
// Function to generate all
// prime numbers upto 10^6
function sieveOfPrimes()
{
// Initialize sieve[] as 1
sieve = Array(1000000).fill(1);
var N = 1000000;
// Iterate over the range [2, N]
for (var i = 2; i * i <= N; i++) {
// If current element is non-prime
if (sieve[i] == 0)
continue;
// Make all multiples of i as 0
for (var j = i * i; j <= N; j += i)
sieve[j] = 0;
}
}
// Function to construct an array A[]
// satisfying the given conditions
function getArray(arr, N)
{
// Stores the resultant array
var A = Array(N).fill(0);
// Stores all prime numbers
var v = [];
// Sieve of Eratosthenes
sieveOfPrimes();
for (var i = 2; i <= 1e5; i++)
// Append the integer i
// if it is a prime
if (sieve[i])
v.push(i);
// Indicates current position
// in list of prime numbers
var j = 0;
// Traverse the array arr[]
for (var i = 0; i < N; i++) {
var ind = arr[i];
// If already filled with
// another prime number
if (A[i] != 0)
continue;
// If A[i] is not filled
// but A[ind] is filled
else if (A[ind] != 0)
// Store A[i] = A[ind]
A[i] = A[ind];
// If none of them were filled
else {
// To make sure A[i] does
// not affect other values,
// store next prime number
var prime = v[j++];
A[i] = prime;
A[ind] = A[i];
}
}
// Print the resultant array
for (var i = 0; i < N; i++) {
document.write( A[i] + " ");
}
}
// Driver Code
var arr = [4, 1, 2, 3, 4];
var N = arr.length;
// Function Call
getArray(arr, N);
</script>
Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)
Similar Reads
Generate Array such that max is minimized and arr[i] != arr[j] when j is a multiple of i Given an integer N, the task is to generate an array arr[] having N positive integers such that arr[i] â arr[j] if j is divisible by i (1-based indexing is considered) such that the maximum value of the sequence is minimum among all possible sequences. Examples: Input: N = 3Output: 1 2 2Explanation:
5 min read
Generate an Array such that the sum of any Subarray is not divisible by its Length Given an integer N. Then the task is to output an array let's say A[] of length N such that: The sum S, of any subarray, let's say A[L, R] where (L != R) must not leave the remainder as 0 when dividing by the length of A[L, R]. Formally, Sum(A[L, R])%(length of A[L, R]) != 0. A[] must contain all un
5 min read
Construct longest Array starting with N and A[i] as multiple of A[i+1] Given an integer N, the task is to construct the longest possible array A[], such that the following conditions hold: A[0] = N.No two adjacent elements should be equal.For all i (0 < i < array length), such that A[i] is divisible by A[i + 1] Note: If there are many possible sequence, print any
8 min read
Generate a sequence with product N such that for every pair of indices (i, j) and i < j, arr[j] is divisible by arr[i] Given a positive integer N, the task is to generate a sequence say arr[] of maximum length having all elements at least 2 such that the product of all the numbers in the sequence is N and for any pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]. Examples: Input: N = 360Output: Maxi
11 min read
Generate an array B[] from the given array A[] which satisfies the given conditions Given an array A[] of N integers such that A[0] + A[1] + A[2] + ... A[N - 1] = 0. The task is to generate an array B[] such that B[i] is either ?A[i] / 2? or ?A[i] / 2? for all valid i and B[0] + B[1] + B[2] + ... + B[N - 1] = 0. Examples: Input: A[] = {1, 2, -5, 3, -1} Output: 0 1 -2 1 0Input: A[]
6 min read
Modify an array such that if 'arr[i]' is 'j' then arr[j] becomes i Given an array arr[] of size n, where all elements are distinct and fall within the range 0 to n-1. The task is to modify arr[] such that if arr[i] = j, then it gets transformed into arr[j] = i.Examples: Input: arr[] = [1, 3, 0, 2]Output: 2 0 3 1Explanation: Since arr[0] = 1, update arr[1] to 0Since
13 min read
Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space Given an array arr[] of size n where every element is in the range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra spaceExamples: Input: arr[] = [3, 2, 0, 1]Output: arr[] = [1, 0, 3, 2]Explanation: arr[arr[0]] is 1 so arr[0] in output
5 min read
Convert an array into another by repeatedly removing the last element and placing it at any arbitrary index Given two arrays A[] and B[], both consisting of a permutation of first N natural numbers, the task is to count the minimum number of times the last array element is required to be shifted to any arbitrary position in the array A[] to make both the arrays A[] and B[] equal. Examples: Input: A[] = {1
6 min read
Count of all possible Arrays such that each array element can be over the range [1, arr[i]] Given an array arr[] consisting of N positive integers, the task is to find the number of all possible arrays such that each array element can be over the range [1, arr[i]] all elements in the newly constructed array must be pairwise distinct. Examples: Input: arr[] = {5}Output: 5Explanation:All pos
5 min read
Rearrange an array such that product of every two consecutive elements is a multiple of 4 Given an array arr[] of size N, the task is to rearrange the array elements such that for every index i(1 <= i <= N - 1), the product of arr[i] and arr[i - 1] is a multiple of 4.Example: Input: arr[] = {1, 10, 100} Output: 1, 100, 10 Explanation: 1 * 100 is divisible by 4 100 * 10 is divisible
11 min read