Prime Arrangements

Count the ways to line up the numbers 1 to n so that every prime stands at a prime position.

Given a whole number n between 1 and 100, count the ways to line up the numbers 1 to n in a row so that every prime number stands at a prime position. Positions are counted from 1. The count grows very large, so return its remainder after dividing by 109 + 7.

Example 1
Input: n = 5
Output: 12
Explanation: [1, 2, 5, 4, 3] is one of the 12. [5, 2, 3, 4, 1] is not, because the prime 5 stands at position 1.
Example 2
Input: n = 100
Output: 682289015
Solution

The Idea

Picture five chairs in a row, numbered 1 to 5, and five cards with the numbers 1 to 5 on them. Each chair gets one card. The chairs are the positions in the row, and the cards are the numbers placed there. Some cards and some chairs carry a prime number: 2, 3 and 5 can each be divided evenly only by 1 and by themselves, while 4 = 2 × 2 cannot, and 1 is not counted as a prime.

The rule says a prime card may only sit on a prime chair. In Example 1, [1, 2, 5, 4, 3] gives chair 1 the card 1, chair 2 the card 2, chair 3 the card 5, and so on. Its prime cards 2, 5 and 3 sit on chairs 2, 3 and 5, so it is allowed. [5, 2, 3, 4, 1] puts the card 5 on chair 1, which is not prime, so it breaks the rule.

There are 5 × 4 × 3 × 2 × 1 = 120 ways to hand out five cards, and the answer says 12 of them follow the rule. Which 12, and how could we count them without writing all 120 down?

The chairs and the cards carry the same numbers, 1 to 5, so there are exactly as many prime chairs as prime cards: three of each. The three prime cards must go on prime chairs, and there are only three of those. So the prime cards fill the prime chairs completely, and the cards 1 and 4 are left for chairs 1 and 4.

The arrangement [1, 2, 5, 4, 3] with positions 2, 3 and 5 in orange and positions 1 and 4 in teal. The prime positions 2, 3, 5 take the primes 2, 3, 5 in 3! = 6 ways, the other positions 1, 4 take the other numbers 1, 4 in 2! = 2 ways, and 6 × 2 = 12.

In the picture, the orange boxes are the prime positions 2, 3 and 5, and the teal boxes are the other positions, 1 and 4. The row labelled "number" shows where [1, 2, 5, 4, 3] puts each card. Every orange position holds a prime, and every teal position holds 1 or 4.

Now the counting splits in two. For the box labelled prime positions 2, 3, 5, position 2 can take any of the three primes, position 3 one of the two left, and position 5 the last one: 3 × 2 × 1 = 6 ways. A product of all whole numbers from a number down to 1 is written with an exclamation mark, so 3 × 2 × 1 is 3! ("3 factorial"). The box labelled other positions 1, 4 has 2! = 2 ways.

The two groups do not affect each other. Each of the 6 ways to seat the primes can go with each of the 2 ways to seat 1 and 4, which gives 6 × 2 = 12, the answer to Example 1. In general, if there are p primes up to n, the answer is p! × (n - p)!.

Solution Approach

The formula p! × (n - p)! replaces listing every arrangement, which is far too slow. It leaves two things to decide: how to count the primes up to n, and how to compute factorials too big to store.

Trying every arrangement

Why not list every arrangement and check each one? For n = 5 that is 120 lists, which is fine. For n = 100 it is 100!, a number with 158 digits, so no program could ever finish. The formula needs only the count of primes.

Counting the primes up to n

How do we find which numbers up to n are prime? Checking each number against every smaller number would work for n ≤ 100, but crossing out multiples does less work. Write down 2 to n, then go from left to right. A number that is not crossed out yet is prime, so count it and cross out its multiples.

Take n = 13. The 2 is not crossed out, so it is prime, and 4, 6, 8, 10 and 12 get crossed out. The 3 is prime, and 9 and 12 get crossed out. The 4 is already crossed out and is skipped. The 5, 7, 11 and 13 stay, giving six primes: 2, 3, 5, 7, 11 and 13.

For 5, the crossing out would start at 5 × 5 = 25, past 13. Smaller multiples such as 10 = 2 × 5 already fell to a smaller prime, so the crossing out for each prime starts at its square. This way of crossing out is called the Sieve of Eratosthenes, named after a Greek scholar.

Factorials that do not fit

How big do the factorials get? For n = 100 there are 25 primes, and 25! × 75! has 135 digits. That is why the problem asks for the remainder after dividing by 1,000,000,007, written 109 + 7 and kept in a constant named MOD.

The remainder of a product depends only on the remainders of its parts. So the factorial can take the remainder after every multiplication and still end with the right result. The running value then stays below MOD, about 109, all the way.

Is that small enough? The next step multiplies a value below 109 + 7 by at most 100, which is about 1011. An int stops a little above 2.1 × 109, so the factorial is kept in a long, which reaches about 9.2 × 1018. The last step multiplies two values below 109 + 7, under 1018, so it fits a long as well.

Java Solution

The method numPrimeArrangements works in these steps:

  1. First, count the primes up to n with a helper method, countPrimesUpTo, and keep the result in primes. The helper makes a boolean array composite of size n + 1, so that composite[n] exists, because n itself may be prime.
  2. Inside the helper, a counter named count starts at 0, and a loop moves i from 2 to n. When composite[i] is still false, i is prime, so count goes up by one. A second loop, inside the first, then marks i * i, i * i + i and so on up to n as crossed out.
  3. Next, compute the two factorials with a second helper, factorial(k). It starts a long named f at 1 and multiplies it by 2, 3 and so on up to k, taking the remainder by MOD after each multiplication.
  4. Finally, multiply factorial(primes) by factorial(n - primes), take the remainder by MOD once more, and return it as an int.

The main method runs both examples, the smallest inputs 1, 2 and 3, and n = 13, and prints the number of primes next to each answer.

Java
public class PrimeArrangements {

    private static final int MOD = 1000000007;

    public static int numPrimeArrangements(int n) {
        int primes = countPrimesUpTo(n);
        // primes! ways for the prime positions, (n - primes)! ways for the rest
        return (int) (factorial(primes) * factorial(n - primes) % MOD);
    }

    private static int countPrimesUpTo(int n) {
        boolean[] composite = new boolean[n + 1];
        int count = 0;
        for (int i = 2; i <= n; i++) {
            if (composite[i]) {
                continue;                        // crossed out: a multiple of a smaller prime
            }
            count++;                             // i is prime
            for (int m = i * i; m <= n; m += i) {
                composite[m] = true;             // cross out the multiples of i
            }
        }
        return count;
    }

    private static long factorial(int k) {
        long f = 1;
        for (int i = 2; i <= k; i++) {
            f = f * i % MOD;                     // f stays below MOD, so f * i fits in a long
        }
        return f;
    }

    public static void main(String[] args) {
        int[] tests = {5, 100, 1, 2, 3, 13};
        for (int n : tests) {
            System.out.println("n = " + n + ": primes = " + countPrimesUpTo(n)
                + ", arrangements = " + numPrimeArrangements(n));
        }
    }
}

Running it prints:

Output
n = 5: primes = 3, arrangements = 12
n = 100: primes = 25, arrangements = 682289015
n = 1: primes = 0, arrangements = 1
n = 2: primes = 1, arrangements = 1
n = 3: primes = 2, arrangements = 2
n = 13: primes = 6, arrangements = 3628800

The line for n = 5 finds the three primes 2, 3 and 5 and gives 12, as in Example 1. The line for n = 100 counts 25 primes, and 25! × 75! leaves the remainder 682289015 from Example 2.

Look at n = 1: there are no primes, yet the answer is 1, the single row [1]. That works because factorial(0) skips its loop and returns 1, and there is one way to seat zero cards. For n = 3 the two rows are [1, 2, 3] and [1, 3, 2], since 1 must stay at position 1.

The last line, n = 13, matches the six primes 2, 3, 5, 7, 11 and 13 found by crossing out multiples. Its answer, 6! × 7! = 720 × 5,040 = 3,628,800, is below MOD, so it is the exact count.

What if f were an int instead of a long? A separate run with that change gives the same 479001600 for 12!. At 13!, though, 479,001,600 × 13 = 6,227,020,800 is too big for an int and wraps around before the remainder is taken. That run gives 932053497 instead of 227020758, and 548916480 for n = 100 instead of 682289015.

Complexity

The sieve runs over 2 to n, and the two factorials need one multiplication per number.

  • Time: O(n log log n), because each prime i crosses out about n / i multiples, and those counts summed over the primes up to n grow like n log log n, while the two factorials together take fewer than n multiplications.
  • Space: O(n), because the composite array holds one entry for each number from 0 to n, while each factorial needs only the single long f.

The sieve has a page of its own in Count Primes.