Skip to content

1175. Prime Arrangements 👎

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  int numPrimeArrangements(int n) {
    const int count = countPrimes(n);
    return factorial(count) * factorial(n - count) % kMod;
  }

 private:
  static constexpr int kMod = 1'000'000'007;

  int countPrimes(int n) {
    vector<bool> prime(n + 1, true);
    prime[0] = false;
    prime[1] = false;
    for (int i = 0; i <= sqrt(n); ++i)
      if (prime[i])
        for (int j = i * i; j <= n; j += i)
          prime[j] = false;
    return ranges::count(prime, true);
  }

  long factorial(int n) {
    long res = 1;
    for (int i = 2; i <= n; ++i)
      res = res * i % kMod;
    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
  public int numPrimeArrangements(int n) {
    final int count = countPrimes(n);
    return (int) (factorial(count) * factorial(n - count) % kMod);
  }

  private static final int kMod = 1_000_000_007;

  private int countPrimes(int n) {
    boolean[] prime = new boolean[n + 1];
    Arrays.fill(prime, 2, n + 1, true);

    for (int i = 0; i * i <= n; ++i)
      if (prime[i])
        for (int j = i * i; j <= n; j += i)
          prime[j] = false;

    int count = 0;

    for (boolean p : prime)
      if (p)
        ++count;

    return count;
  }

  private long factorial(int n) {
    long res = 1;
    for (int i = 2; i <= n; ++i)
      res = res * i % kMod;
    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def numPrimeArrangements(self, n: int) -> int:
    kMod = 1_000_000_007

    def factorial(n: int) -> int:
      fact = 1
      for i in range(2, n + 1):
        fact = fact * i % kMod
      return fact

    count = self._countPrimes(n)
    return factorial(count) * factorial(n - count) % kMod

  def _countPrimes(self, n: int) -> int:
    isPrime = [False] * 2 + [True] * (n - 1)
    for i in range(2, int(n**0.5) + 1):
      if isPrime[i]:
        for j in range(i * i, n + 1, i):
          isPrime[j] = False
    return sum(isPrime)