본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1175. Prime Arrangements

반응형

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;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.