https://school.programmers.co.kr/learn/courses/30/lessons/120848
i팩토리얼 (i!)은 1부터 i까지 정수의 곱을 의미합니다.
예를들어 5! = 5 4 3 2 1 = 120 입니다.
정수 n이 주어질 때 다음 조건을 만족하는 가장 큰 정수 i
를 return 하도록 solution 함수를 완성해주세요.
i! ≤ n
0 < n ≤ 3,628,800
n | result |
---|---|
3628800 | 10 |
7 | 3 |
10! = 3,628,800입니다. n이 3628800이므로 최대 팩토리얼인 10을 return 합니다.
3! = 6, 4! = 24입니다. n이 7이므로, 7 이하의 최대 팩토리얼인 3을 return 합니다.
class Solution {
public int solution(int n) {
int answer=0;
int i=0;
int near1=0;
int near2=0;
boolean forRoop=true;
while(forRoop){
i=i+1;
near1 = fact(i);
near2=fact(i+1);
if(near1<=n && n<=near2){
forRoop=false;
}
}
if(near2==n){
answer=i+1;
}
else{
answer=i;
}
return answer;
}
public static int fact(int n){
int count=0;
if(n==1){
count=1;
}
else{
count=n*fact(n-1);
}
return count;
}
}
n보다 크거나 같은 i가 생길 때 까지 while문을 반복해주었다.
제한사항으로 인해 i!<=n 이 되므로, 만약 n이랑 (i+1)!이 같으면.
예를 들어 예시에 있는 10!처럼 되면 answer은 i+1이고, 같지 않다면
다 n보다 작은 i! 의 i값을 반환해준다.