Given a number N, task is to Check whether it is a permutable prime number or not. A Permutable prime number is that number which after switching the position of digits through any permutation is also prime. Some of the permutable prime numbers are 2, 3, 5, 7, 11, etc. Prerequisites : Primality Test | CPP next_permute() Examples :
Input : 31 Output : Yes Explanation : Both 13 and 31 are prime. Input : 19 Output : No Explanation : 19 is prime but 91 is not
Approach : 1) Construct Sieve of Eratosthenes to find the prime numbers efficiently. 2) Either generate every permutation of the number by switching its digits or use inbuilt C++ function next_permutation to check whether it is prime 3) If any permutation of digits is not prime, simply answer is NO, otherwise YES. Below is the implementation of above approach.Â
C++
// CPP Program to check whether number is// permutable prime or not#include <bits/stdc++.h>using namespace std;Â
#define MAX 1000001Â
// Sieve of Eratosthenes to find the// prime numbers upto MAX efficientlyvoid sieveOfEratosthenes(bool* primes){    // 1 is neither prime nor composite    primes[1] = false;Â
    for (int i = 2; i * i < MAX; i++) {Â
        // If prime[i] is not changed,        // then it is a prime        if (primes[i] == true) {Â
            // Update all multiples of i            for (int j = i * 2; j < MAX; j += i)                primes[j] = false;        }    }}Â
// Function returns 1 if the number N is// permutable prime otherwise notbool checkPermutablePrime(int N){    // Boolean Array for prime numbers    bool primes[MAX];Â
    // Initialize all entries as true.    // A value in prime[i] will finally    // be false if i is not a prime,    // else true.    memset(primes, true, sizeof(primes));Â
    sieveOfEratosthenes(primes);Â
    // Creating Array to store digits    int num[7];Â
    // Convert the number into array of digits    int pos = 0;    while (N > 0) {        num[pos++] = N % 10;        N /= 10;    }Â
    // Size of Array    int SZ = pos;    int flag = 0;Â
    sort(num, num + SZ);Â
    do {Â
        // Construct the number again        // from array of digits        int temp = 0;        pos = 0;        while (pos < SZ) {            temp = temp * 10 + num[pos];            pos++;        }Â
        // check if it is prime of not        if (primes[temp] == false) {            flag = 1;            break;        }    } while (next_permutation(num, num + SZ));Â
    // If flag is 1, number    // is not permutable prime    if (flag)        return false;Â
    return true;}Â
// Driver Code to check above functionsint main(){Â Â Â Â int N = 31;Â Â Â Â cout << (checkPermutablePrime(N) == 1 ? Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "Yes" : "No") << endl;Â
    N = 19;    cout << (checkPermutablePrime(N) == 1 ?                       "Yes" : "No") << endl;    return 0;} |
Java
import java.util.Arrays;Â
public class PermutablePrime {Â
    // Define the maximum limit for the sieve of Eratosthenes    static final int MAX = 1000001;Â
    // Create a boolean array to store the prime numbers    static boolean[] primes = new boolean[MAX];Â
    // Sieve of Eratosthenes algorithm to find all prime numbers    static void sieveOfEratosthenes() {        // Initialize all values in the array to true        Arrays.fill(primes, true);Â
        // Mark 1 as not prime        primes[1] = false;Â
        // Loop through all values from 2 to sqrt(MAX) and mark multiples as not prime        for (int i = 2; i * i < MAX; i++) {            if (primes[i]) {                for (int j = i * 2; j < MAX; j += i) {                    primes[j] = false;                }            }        }    }Â
    // Function to check if a number is permutable prime    static boolean checkPermutablePrime(int N) {        // Reset the primes array and run the sieve of Eratosthenes algorithm        Arrays.fill(primes, true);        sieveOfEratosthenes();Â
        // Create an array to store the digits of the number        int[] num = new int[7];        int pos = 0;        while (N > 0) {            num[pos++] = N % 10;            N /= 10;        }        int SZ = pos;Â
        // Flag to check if any permutation of the number is not prime        int flag = 0;Â
        // Sort the digits of the number in ascending order and generate all permutations        Arrays.sort(num, 0, SZ);        do {            // Convert the current permutation to a number and check if it is not prime            int temp = 0;            pos = 0;            while (pos < SZ) {                temp = temp * 10 + num[pos];                pos++;            }            if (!primes[temp]) {                flag = 1;                break;            }        } while (nextPermutation(num, SZ));Â
        // If any permutation is not prime, return false        if (flag == 1) {            return false;        }Â
        // Otherwise, return true        return true;    }Â
    // Function to generate the next permutation of an array of integers    static boolean nextPermutation(int[] num, int SZ) {        int i = SZ - 2;Â
        // Find the index of the first element from the right that is smaller than its next element        while (i >= 0 && num[i] >= num[i + 1]) {            i--;        }Â
        // If no such element is found, the array is already in descending order and has no next permutation        if (i == -1) {            return false;        }Â
        // Find the index of the smallest element from the right that is greater than the above element        int j = SZ - 1;        while (num[j] <= num[i]) {            j--;        }Â
        // Swap the above two elements        int temp = num[i];        num[i] = num[j];        num[j] = temp;Â
        // Reverse the order of the remaining elements to generate the next lexicographically larger permutation        int left = i + 1, right = SZ - 1;        while (left < right) {            temp = num[left];            num[left++] = num[right];            num[right--] = temp;        }        return true;    }Â
// driver code     public static void main(String[] args)    {        int N = 31;        System.out.println(checkPermutablePrime(N) ? "Yes" : "No");        N = 19;        System.out.println(checkPermutablePrime(N) ? "Yes" : "No");    }} // this code contributed by devendra            |
Python3
# Python3 Program to check whether number is# permutable prime or notimport itertoolsMAX = 1000001Â
# Sieve of Eratosthenes to find the# prime numbers upto MAX efficientlydef sieveOfEratosthenes(primes):         # 1 is neither prime nor composite    primes[1] = False;Â
    for i in range(2, int(MAX ** 0.5) + 1): Â
        # If prime[i] is not changed,        # then it is a prime        if (primes[i] == True): Â
            # Update all multiples of i            for j in range(i + i, MAX, i):                primes[j] = False;         return primesÂ
# Function returns 1 if the number N is# permutable prime otherwise notdef checkPermutablePrime(N):Â
    # Boolean Array for prime numbers    primes = [True for _ in range(MAX)]         primes = sieveOfEratosthenes(primes);Â
    # Creating Array to store digits    num = list(map(int, str(N)))              # Creating all permutations of the list    permutations = list(itertools.permutations(num));Â
    ind = 0         flag = 0    for num in permutations:Â
        # Construct the number again        # from array of digits        temp = int("".join(list(map(str, num))))Â
        # check if it is prime of not        if (primes[temp] == False):             flag = 1;            break;         # If flag is 1, number    # is not permutable prime    return not flagÂ
# Driver Code to check above functionsN = 31;print(["No", "Yes"][checkPermutablePrime(N) == 1])Â
N = 19;print(["No", "Yes"][checkPermutablePrime(N) == 1])Â
# This code is contributed by phasing17 |
C#
using System;Â
class PermutablePrime {    // Define the maximum limit for the sieve of    // Eratosthenes    static readonly int MAX = 1000001;Â
    // Create a boolean array to store the prime numbers    static bool[] primes = new bool[MAX];Â
    // Sieve of Eratosthenes algorithm to find all prime    // numbers    static void SieveOfEratosthenes()    {        // Initialize all values in the array to true        Array.Fill(primes, true);Â
        // Mark 1 as not prime        primes[1] = false;Â
        // Loop through all values from 2 to sqrt(MAX) and        // mark multiples as not prime        for (int i = 2; i * i < MAX; i++) {            if (primes[i]) {                for (int j = i * 2; j < MAX; j += i) {                    primes[j] = false;                }            }        }    }Â
    // Function to check if a number is permutable prime    static bool CheckPermutablePrime(int N)    {        // Reset the primes array and run the sieve of        // Eratosthenes algorithm        Array.Fill(primes, true);        SieveOfEratosthenes();Â
        // Create an array to store the digits of the number        int[] num = new int[7];        int pos = 0;        while (N > 0) {            num[pos++] = N % 10;            N /= 10;        }        int SZ = pos;Â
        // Flag to check if any permutation of the number is        // not prime        int flag = 0;Â
        // Sort the digits of the number in ascending order        // and generate all permutations        Array.Sort(num, 0, SZ);        do {            // Convert the current permutation to a number            // and check if it is not prime            int temp = 0;            pos = 0;            while (pos < SZ) {                temp = temp * 10 + num[pos];                pos++;            }            if (!primes[temp]) {                flag = 1;                break;            }        } while (NextPermutation(num, SZ));Â
        // If any permutation is not prime, return false        if (flag == 1) {            return false;        }Â
        // Otherwise, return true        return true;    }Â
    // Function to generate the next permutation of an array    // of integers    static bool NextPermutation(int[] num, int SZ)    {        int i = SZ - 2;Â
        // Find the index of the first element from the        // right that is smaller than its next element        while (i >= 0 && num[i] >= num[i + 1]) {            i--;        }Â
        // If no such element is found, the array is already        // in descending order and has no next permutation        if (i == -1) {            return false;        }Â
        // Find the index of the smallest element from the        // right that is greater than the above element        int j = SZ - 1;        while (num[j] <= num[i]) {            j--;        }Â
        // Swap the above two elements        int temp = num[i];        num[i] = num[j];        num[j] = temp;Â
        // Reverse the order of the remaining elements to        // generate the next lexicographically larger        // permutation        int left = i + 1, right = SZ - 1;        while (left < right) {            temp = num[left];            num[left++] = num[right];            num[right--] = temp;        }        return true;    }Â
    // driver code    public static void Main(string[] args)    {        int N = 31;        Console.WriteLine(CheckPermutablePrime(N) ? "Yes"                                                  : "No");        N = 19;        Console.WriteLine(CheckPermutablePrime(N) ? "Yes"                                                  : "No");    }}Â
// this code contributed by phasing17 |
PHP
<?php// PHP Program to check // whether number is// permutable prime or not$MAX = 100001;$zz;$l = 0;Â
// to find all permutation// of that numberfunction next_permutation($items,                           $perms = array( )) {    global $zz, $l;    if (empty($items))     {         $zz[$l++] = join($perms);    }          else    {        for ($i = count($items) - 1;              $i >= 0; --$i)         {            $newitems = $items;            $newperms = $perms;            list($foo) = array_splice($newitems, $i, 1);            array_unshift($newperms, $foo);            next_permutation($newitems, $newperms);        }    }    return $zz;}Â
// Sieve of Eratosthenes to // find the prime numbers // upto MAX efficientlyfunction sieveOfEratosthenes($primes){    global $MAX;         // 1 is neither prime     // nor composite    $primes[1] = false;Â
    for ($i = 2; $i * $i < $MAX; $i++)    {Â
        // If prime[i] is not changed,        // then it is a prime        if ($primes[$i] == true)        {Â
            // Update all multiples of i            for ($j = $i * 2;                  $j < $MAX; $j += $i)                $primes[$j] = false;        }    }    return $primes;}Â
// Function returns 1 if the // number N is permutable// prime otherwise notfunction checkPermutablePrime($N){    global $MAX, $zz, $l;         // Boolean Array for    // prime numbersÂ
    // Initialize all entries     // as true. A value in     // prime[i] will finally    // be false if i is not a     // prime, else true.    $primes = array_fill(0, $MAX, true);Â
    $primes = sieveOfEratosthenes($primes);Â
    // Creating Array     // to store digits    $num = array();Â
    // Convert the number     // into array of digits    $pos = 0;    while ($N > 0)     {        $num[$pos++] = $N % 10;        $N = (int)($N / 10);    }Â
    // Size of Array    $flag = 0;Â
    sort($num);    $num1 = next_permutation($num);    $i = 0;    while ($i < count($num1))    {Â
        // Construct the number again        // from array of digits        $temp = 0;        $pos = 0;        while ($pos < strlen($num1[$i]))         {            $temp = $temp * 10 +                 ord($num1[$i][$pos]) - 48;            $pos++;        }Â
        // check if it is        // prime of not        if ($primes[$temp] == false)        {            $flag = 1;            break;        }        $i++;    }         $zz = array();    $l = 0;Â
    // If flag is 1, number    // is not permutable prime    if ($flag)        return false;Â
    return true;}Â
// Driver Code$N = 31;echo (checkPermutablePrime($N) == 1 ? Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "Yes" : "No") . "\n";Â
$N = 19;echo (checkPermutablePrime($N) == 1 ? Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "Yes" : "No") . "\n";Â
// This Code is contributed// by mits?> |
Javascript
// JavaScript Program to check whether number is// permutable prime or notÂ
Â
let MAX = 1000001Â
Â
// Function to calculate and store all// the next permutations of an arrayconst permutator = (nums) => {Â Â let permutations = [];Â
  const permute = (arr, m = []) => {    if (arr.length === 0) {      permutations.push(m)    } else {      for (let i = 0; i < arr.length; i++) {        let curr = arr.slice();        let next = curr.splice(i, 1);        permute(curr.slice(), m.concat(next))     }   } }Â
 permute(nums)Â
 return permutations;}Â
// Sieve of Eratosthenes to find the// prime numbers upto MAX efficientlyfunction sieveOfEratosthenes(primes){    // 1 is neither prime nor composite    primes[1] = false;Â
    for (var i = 2; i * i < MAX; i++) {Â
        // If prime[i] is not changed,        // then it is a prime        if (primes[i] == true) {Â
            // Update all multiples of i            for (var j = i * 2; j < MAX; j += i)                primes[j] = false;        }    }}Â
// Function returns 1 if the number N is// permutable prime otherwise notfunction checkPermutablePrime(N){    // Boolean Array for prime numbers    let primes = new Array(MAX).fill(true);Â
Â
    sieveOfEratosthenes(primes);Â
    // Creating Array to store digits    let num = new Array(7);Â
    // Convert the number into array of digits    let pos = 0;    while (N > 0) {        num[pos++] = N % 10;        N = Math.floor(N / 10);    }Â
    // Size of Array    let SZ = pos;    let flag = 0;Â
    num.sort();         var ind = 0;         let permutations = permutator(num);         do {Â
        // Construct the number again        // from array of digits        let temp = 0;        pos = 0;        while (pos < SZ) {            temp = temp * 10 + num[pos];            pos++;        }Â
        // check if it is prime of not        if (primes[temp] == false) {            flag = 1;            break;        }        num = permutations[ind++];    } while (ind < permutations.length)Â
    // If flag is 1, number    // is not permutable prime    if (flag)        return false;Â
    return true;}Â
// Driver Code to check above functionslet N = 31;console.log((checkPermutablePrime(N) == 1 ? Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "Yes" : "No"));Â
N = 19;console.log((checkPermutablePrime(N) == 1 ? Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "Yes" : "No"));Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
Â
// This code is contributed by phasing17 |
Yes No
Time Complexity : O(n * log(log(n)) + n!). The sieve of Eratosthenes has a time complexity of O(n * log(log(n))) for finding all primes up to a given number, and the checking for permutations of the digits has a time complexity of O(n!), where n is the number of digits in the input number.
space complexity :O(n), where n is the number of integers up to MAX. This is because the program uses an array of size MAX to store the prime numbers found by the Sieve of Eratosthenes.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Here you can find 54409 more Information on that Topic: geeksforgeeks.org/check-a-number-for-permutable-prime/ […]
… [Trackback]
[…] Find More Information here on that Topic: geeksforgeeks.org/check-a-number-for-permutable-prime/ […]
… [Trackback]
[…] Read More to that Topic: geeksforgeeks.org/check-a-number-for-permutable-prime/ […]