📌  相关文章
📜  从数组arr []生成一个N长度的数组A [],使arr [i]是由A [i]的倍数组成的最后一个索引

📅  最后修改于: 2021-05-17 21:49:02             🧑  作者: Mango

给定一个数组 ARR []的长度为N,其值小于N时,所述任务是构造相同的长度的另一个数组A [],使得对于在所述阵列A []i元素,ARR [i]是最后一个索引(1基于索引的)由A [i]的倍数组成。

例子:

方法:想法是将质数作为数组元素放置在满足条件的所需索引中。请按照以下步骤解决问题:

  • 使用Eratosthenes筛生成所有素数 并将其存储在另一个数组中。
  • {0}初始化数组A []以存储所需的数组。
  • 遍历数组arr []并执行以下步骤:
    • 检查A [arr [i]]是否为非零值,但A [i]为0。如果确定为true,则分配A [i] = A [arr [i]]。
    • 检查A [arr [i]]A [i]是否均为0。如果发现为真,则将与已经分配的数组元素不同的质数分配给两个索引arr [i]i
  • 完成上述步骤后,打印数组A []的元素。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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 v;
 
    // Sieve of Erastosthenes
    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 v
            = new ArrayList();
 
    // Sieve of Erastosthenes
    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 Erastosthenes
    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
 
    # Prthe 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 v
      = new List();
 
    // Sieve of Erastosthenes
    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.


输出:
2 3 5 7 2

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