Post

[Programmers] #120848 - 팩토리얼 [Java][C++][Python]

[Programmers] #120848 - 팩토리얼 [Java][C++][Python]

문제 링크


1. 아이디어

$i! \le n$을 만족하는 가장 큰 $i$를 구하는 문제다. $i!$는 $i$가 커질수록 계속 커지므로 조건을 만족하는 $i$는 1부터 이어지고 그 끝이 답이다. $n$이 $10! = 3{,}628{,}800$ 이하라 $i$는 10을 넘지 않으므로 $1!$부터 $10!$까지만 계산해 두고 그중 $n$ 이하인 가장 큰 $i$를 고른다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int solution(int n) {
        int[] fact = new int[1 + 10];
        fact[0] = 1;

        for (int i = 1; i <= 10; i++) {
            fact[i] = fact[i - 1] * i;
        }

        for (int i = 10; i >= 1; i--) {
            if (fact[i] <= n) return i;
        }

        return -1;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

int fact[1 + 10] = {1};

int solution(int n) {
    for (int i = 1; i <= 10; i++) {
        fact[i] = fact[i - 1] * i;
    }

    for (int i = 10; i >= 1; i--) {
        if (fact[i] <= n) return i;
    }

    return -1;
}
1
2
3
4
5
import math


def solution(n):
    return max(i for i in range(1, 11) if math.factorial(i) <= n)

This post is licensed under CC BY 4.0 by the author.