forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1175.java
46 lines (40 loc) · 1.46 KB
/
_1175.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.fishercoder.solutions;
import java.math.BigInteger;
import java.util.Arrays;
public class _1175 {
public static class Solution1 {
//credit: https://leetcode.com/problems/prime-arrangements/discuss/371884/Simple-Java-With-comment-sieve_of_eratosthenes
static int MOD = 1000000007;
public static int numPrimeArrangements(int n) {
int numberOfPrimes = generatePrimes(n);
BigInteger x = factorial(numberOfPrimes);
BigInteger y = factorial(n - numberOfPrimes);
return x.multiply(y).mod(BigInteger.valueOf(MOD)).intValue();
}
public static BigInteger factorial(int n) {
BigInteger fac = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
fac = fac.multiply(BigInteger.valueOf(i));
}
return fac.mod(BigInteger.valueOf(MOD));
}
public static int generatePrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, 2, n + 1, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
int count = 0;
for (int i = 0; i < prime.length; i++) {
if (prime[i]) {
count++;
}
}
return count;
}
}
}