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 nn
Example 1
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
Output: 682289015
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][5, 2, 3, 4, 1]
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.
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]
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
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 nn
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
Is that small enough? The next step multiplies a value below 109 + 7 by at most 100, which is about 1011. An intlonglong
Java Solution
The method numPrimeArrangements
- First, count the primes up to
with a helper method,n , and keep the result incountPrimesUpTo . The helper makes aprimes arrayboolean of sizecomposite , so thatn + 1 exists, becausecomposite[n] itself may be prime.n - Inside the helper, a counter named
starts at 0, and a loop movescount from 2 toi . Whenn is still false,composite[i] is prime, soi goes up by one. A second loop, inside the first, then markscount ,i * i and so on up toi * i + i as crossed out.n - Next, compute the two factorials with a second helper,
. It starts afactorial(k) namedlong at 1 and multiplies it by 2, 3 and so on up tof , taking the remainder byk after each multiplication.MOD - Finally, multiply
byfactorial(primes) , take the remainder byfactorial(n - primes) once more, and return it as anMOD .int
The main
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:
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]factorial(0)[1, 2, 3][1, 3, 2]
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
What if fintlongint
Complexity
The sieve runs over 2 to n
- 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
array holds one entry for each number from 0 to n, while each factorial needs only the singlecompositelong .f
The sieve has a page of its own in