-
[프로그래머스] 코테 (팩토리얼)헬리'Daily/꾸준한 알고리즘 2023. 7. 22. 13:03728x90
코딩테스트를 푸는데...
역시 어렵다..!
쉽지않지아주..!
그치만 오늘 풀면서 알게된것을 정리해 보려고 한다.
문제는 프로그래머스의 문제를 가져왔다!
팩토리얼
문제) i팩토리얼 (i!)은 1부터 i까지 정수의 곱을 의미합니다. 예를들어 5! = 5 * 4 * 3 * 2 * 1 = 120 입니다.
정수 n이 주어질 때 다음 조건을 만족하는 가장 큰 정수 i를 return 하도록 solution 함수를 완성해주세요.조건 : i! <=n
입출력 예
n result 3628800 10 7 3 3! =6 으로, 7보다 작다.
4! =24 이므로, 7보다 크다.
10! = 3,628,800이므로, n이 3628800이므로 최대 팩토리얼인 10을 return 한다.
function solution(n) { let i = 1; let factorial = 1; while(factorial <= n){ i +=1 factorial *= i } return i; }
while (factorial <= n)보다 작거나 같을때 까지
i에게는 1씩 증가시키고,
factorial에 i를 곱해준다.
이렇게 하게되면
테스트 1 입력값 〉 3628800 기댓값 〉 10 실행 결과 〉 실행한 결괏값 11이 기댓값 10과 다릅니다. 테스트 2 입력값 〉 7 기댓값 〉 3 실행 결과 〉 실행한 결괏값 4이 기댓값 3과 다릅니다. 이러한 결과를 받을 수 있는데,
이러한 값이 나오게 된 이유를 살펴보았다.
만약 n에 120 이라는 숫자를 넣는경우,
i f f <= 120 1 1 1 <= 120 2 2 (이 전 factorial 수와 곱해진 것) 2 <= 120 3 6 (2*3) 6 <= 120 4 24 (6*4) 24 <= 120 5 120 (24*5) 120 <= 120 이 표를 보면,
5*24를 했을때, 120은 120과 같기 때문에
반복문안에서 계속 반복하는것이 아닌,
그 다음 함수인 i += 1을거치게 되면 답은 5가 아닌 6이 되어버린다.
그리고 factorial *=i 를 거치게 되면 6을 곱하게 되는데, 곱한값은 720(120*6)이 된다.
720 <=120이 false 이므로 반복문을 탈출하게 되고,
그 후 에 i를 출력하므로, 1이 더 증가된 값이 나오게된다.
그래서
function solution(n) { let i = 1; let factorial = 1; while(factorial <= n){ i +=1 factorial *= i } return i-1; }
로 해주면
테스트 1 입력값 〉 3628800 기댓값 〉 10 실행 결과 〉 테스트를 통과하였습니다. 테스트 2 입력값 〉 7 기댓값 〉 3 실행 결과 〉 테스트를 통과하였습니다. 통과~
728x90'헬리'Daily > 꾸준한 알고리즘' 카테고리의 다른 글
[프로그래머스] 코테 (편지) (0) 2023.07.28 [프로그래머스] 코테 (k의 개수) (0) 2023.07.27 알고리즘문제 5 (0) 2023.05.29 알고리즘문제 4 (0) 2023.05.29 알고리즘문제 3 (0) 2023.05.29