![]() |
Given an array, our task is to Reverse all prime numbers in an array without affecting other elements in Python. Examples: Input : arr = {1, 2, 3, 4, 5, 6} Output : {1,5,3,4,2,6} Explanation: Prime elements in given array are 2,3,5. After reversing the modified array will be {1,5,3,4,2,6} Approach:
Below is the implementation of the above approach Python3
Output
[1, 5, 3, 4, 2, 6] Complexity Analysis: Let x be the largest prime number in the array. Time complexity: O(n*sqrt(x)) METHOD 2: Using a sieve method. APPROACH: The “reverse_primes_4” function takes an input array “arr” and returns a new array with all the prime numbers in “arr” reversed while keeping the non-prime numbers in their original position. It uses a sieve of Eratosthenes algorithm to generate a list of primes up to the maximum value in “arr”, and then reverses this list. It then iterates through “arr”, swaps any prime numbers it finds with the first prime in the reversed list, and removes that prime from the reversed list. ALGORITHM: 1. Use a sieve to generate a list of primes up to the maximum element in the input array. Python3
Output
[1, 5, 3, 4, 2, 6] Time complexity: O(n*log(log(n))), where n is the maximum element in the input array (due to the time complexity of the sieve algorithm) |
Reffered: https://www.geeksforgeeks.org
Data Structures |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |