Leetcode 1175. Prime Arrangements
Given an integer n
, return the number of prime arrangements. Since the answer may be large, return the answer modulo 10^9 + 7.
A prime arrangement is an arrangement of the integers 1
to n
such that:
n
will be in the range 1
to 100
.10^9 + 7
.1
is considered a prime number (it is not).1
when counting prime positions.n
.n
.10^9 + 7
.#include <iostream>
#include <vector>
#include <algorithm>
const int MOD = 1'000'000'007;
int countPrimes(int n) {
if (n < 2) return 0;
std::vector<bool> isPrime(n + 1, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; ++i) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return std::count(isPrime.begin(), isPrime.end(), true);
}
long long factorial(int n) {
long long result = 1;
for (int i = 2; i <= n; ++i) {
result = (result * i) % MOD;
}
return result;
}
int numPrimeArrangements(int n) {
int primeCount = countPrimes(n);
int nonPrimeCount = n - primeCount;
long long primeFactorial = factorial(primeCount);
long long nonPrimeFactorial = factorial(nonPrimeCount);
return (primeFactorial * nonPrimeFactorial) % MOD;
}
int main() {
int n;
std::cin >> n;
std::cout << numPrimeArrangements(n) << std::endl;
return 0;
}
This complexity is efficient given the constraint that n
is at most 100
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?