 Open in App
Not now

# Python Program to Reverse all Prime Numbers in Array Without Affecting Elements

• Last Updated : 07 Nov, 2022

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:

• Start traversing the array from left to right.
• Maintain another array for storing prime numbers.
• If the current element is prime then append the current element to the prime array.
• Start traversing the array again and replace the prime element with the element present in the prime array from the last.
• Finally, return the modified array.

Below is the implementation of the above approach

## Python3

 `from` `math ``import` `sqrt ` `# Function to check element is prime ` ` `  ` `  `def` `isPrime(x): ` `# flag maintains status if x is prime ` `    ``prime ``=` `0` `    ``if``(x > ``1``): ` `        ``for` `i ``in` `range``(``2``, ``int``(sqrt(x)) ``+` `1``): ` `            ``if` `(x ``%` `i ``=``=` `0``): ` `                ``prime ``=` `1` `                ``break` `        ``if` `(prime ``=``=` `0``): ` `            ``return` `True` `        ``else``: ` `            ``return` `False` `    ``else``: ` `        ``return` `False` ` `  ` `  `def` `reversePrimes(arr): ` `    ``n ``=` `len``(arr) ` `    ``# array to store prime elements ` `    ``prime ``=` `[] ` `    ``for` `i ``in` `range``(n): ` `        ``if` `isPrime(arr[i]): ` `            ``prime.append(arr[i]) ` `    ``# variable to store index of prime array ` `    ``k ``=` `len``(prime)``-``1` `    ``# Traversing again to modify the array ` `    ``for` `i ``in` `range``(n): ` `        ``if` `isPrime(arr[i]): ` `            ``arr[i] ``=` `prime[k] ` `            ``k ``=` `k``-``1` `    ``return` `arr ` ` `  ` `  `print``(reversePrimes([``1``, ``2``, ``3``, ``4``, ``5``, ``6``])) `

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))

Space Complexity: O(n) for storing prime elements

My Personal Notes arrow_drop_up
Related Articles