import java.util.ArrayList;
import java.util.List;

public class MagnanimousNumbers {

    public static void main(String[] args) {
        runTask("Find and display the first 45 magnanimous numbers.", 1, 45);
        runTask("241st through 250th magnanimous numbers.", 241, 250);
        runTask("391st through 400th magnanimous numbers.", 391, 400);
    }

    private static void runTask(String message, int startN, int endN) {
        int count = 0;
        List<Integer> nums = new ArrayList<>();
        for ( int n = 0 ; count < endN ; n++ ) {
            if ( isMagnanimous(n) ) {
                nums.add(n);
                count++;
            }
        }
        System.out.printf("%s%n", message);
        System.out.printf("%s%n%n", nums.subList(startN-1, endN));
    }

    private static boolean isMagnanimous(long n) {
        if ( n >= 0 && n <= 9 ) {
            return true;
        }
        long q = 11;
        for ( long div = 10 ; q >= 10 ; div *= 10 ) {
            q = n / div;
            long r = n % div;
            if ( ! isPrime(q+r) ) {
                return false;
            }
        }
        return true;
    }

    private static final int MAX = 100_000;
    private static final boolean[] primes = new boolean[MAX];
    private static boolean SIEVE_COMPLETE = false;

    private static final boolean isPrimeTrivial(long test) {
        if ( ! SIEVE_COMPLETE ) {
            sieve();
            SIEVE_COMPLETE = true;
        }
        return primes[(int) test];
    }

    private static final void sieve() {