반응형
https://leetcode.com/problems/prime-arrangements/description/
Prime Arrangements - LeetCode
Can you solve this real interview question? Prime Arrangements - Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be writte
leetcode.com
소수를 판별해 순열을 구하는 문제였습니다.
📕 풀이방법
📔 풀이과정
n까지의 소수를 구해 primeCount에 저장합니다.
📔 정답 출력 | 반환
valid 한 순열을 구하기 위해 primeCount의 순열 * (n - primeCount)의 순열을 MOD로 나눈 나머지를 반환합니다.
📕 Code
📔 C++
using ll = long long;
const int MOD = 1e9 + 7;
class Solution {
public:
bool isPrime(int n) {
if (n == 1) return false;
for(int i = 2; i * i <= n; i++) {
if(n % i == 0) return false;
}
return true;
}
ll factorial(int n) {
ll fac = 1;
for(int i = 2; i <= n; i++) fac = (fac * i) % MOD;
return fac;
}
int numPrimeArrangements(int n) {
int primeCount = 0;
for(int i = 2; i <= n; i++) {
if (isPrime(i)) primeCount++;
}
return ((factorial(primeCount) % MOD) * (factorial(n - primeCount) % MOD)) % MOD;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1189. Maximum Number of Balloons (1) | 2023.11.29 |
---|---|
(C++) - LeetCode (easy) 1184. Distance Between Bus Stops (0) | 2023.11.27 |
(C++) - LeetCode (easy) 1154. Day of the Year (0) | 2023.11.14 |
(C++) - LeetCode (easy) 1103. Distribute Candies to People (0) | 2023.10.30 |
(C++) - LeetCode (easy) 1089. Duplicate Zeros (0) | 2023.10.27 |