Euler Problem 41

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

Make a big list of primes. Check if primes are pandigital to 7 digits. Sort the list. Pick the biggest. Done.

import java.util.*;

public class Euler41
{
    public static void main(String[] args)
    {
        System.out.format(“Problem 41:\n”);
        Euler41 e = new Euler41();
        System.out.format(“Answer = %s\n”, e.Problem());
    }
    public String Problem ()
    {
        ArrayList<String> P = new ArrayList<String>();
        String [] D = {“1″,”2″,”3″,”4″,”5″,”6″,”7”};
        boolean flag = true;
        int n = 10000000;
        boolean [] isPrime = new boolean [n+1];
        for (int i = 2; i < n; i++)
            isPrime[i] = true;
        for (int p = 2; p*p < n; p++)
            if (isPrime[p] == true)
                for (int m = p*p; m < n; m = m+p)
                    if (m % p == 0)
                        isPrime[m] = false;
        for (int i = 2; i < n; i++)
            if (isPrime[i] == true)
            {
                String p = Integer.toString(i);
                flag = true;
                for (String d: D)
                    if(p.replace(d,””).length() != p.length()-1)
                        flag = false;
                if (flag)
                    P.add(p);
            }
        Collections.sort(P);
        return String.valueOf(P.get(P.size()-1));
    }
}

 



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s