Count all prime numbers that can be formed using digits of a given number

by Nitikesh Pattanayak
208 views
A+A-
Reset

import java.util.*;

  

public class GFG {

    static HashSet<String> H = new HashSet<>();

  

    

    

    static boolean check(String number)

    {

        if (number.length() == 0) {

            return false;

        }

        number = number.trim();

        long num = Long.parseLong(number);

  

        

        if (num == 1) {

            return false;

        }

        if (num % 2 == 0 && num != 2) {

            return false;

        }

        if (num % 3 == 0 && num != 3) {

            return false;

        }

  

        

        for (int i = 6; i * i <= num; i += 6) {

            if (num % (i - 1) == 0 || num % (i + 1) == 0) {

                return false;

            }

        }

  

        

        return true;

    }

  

    

    

    static void DFS(int arr[], String ans)

    {

        

        if (check(ans) == true) {

            H.add(ans);

        }

  

        for (int i = 0; i <= 9; ++i) {

            if (arr[i] == 0) {

                continue;

            }

  

            

            ans += i;

  

            

            arr[i]--;

  

            

            DFS(arr, ans);

            ans = ans.substring(

                0, ans.length() - 1);

  

            

            arr[i]++;

        }

    }

  

    

    public static void main(String[] args)

    {

        String number = "123";

  

        int count[] = new int[10];

        for (int i = 0; i < number.length(); ++i) {

            count[number.charAt(i) - 48]++;

        }

  

        

        DFS(count, "");

  

        

        System.out.println(H.size());

    }

}

You may also like

Leave a Reply

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00
Verified by MonsterInsights