개발👩💻/알고리즘
백준 js 10872: 팩토리얼
gigibean
2021. 5. 6. 14:34
728x90
const input =주어진 값
const getFactorial = (n) => {
let result = 1;
for (let i = 1; i <= n; i++){
result *= i;
}
return result;
}
문제
0보다 크거나 같은 정수 N이 주어진다. 이때, N!을 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 정수 N(0 ≤ N ≤ 12)가 주어진다.
출력
첫째 줄에 N!을 출력한다.
예제 입력 1
10
예제 출력 1
3628800
예제 입력 2
0
예제 출력 2
1
풀이
루프문을 이용해 그 수만큼 곱해서 팩토리얼을 반환하면 된다. 이렇게하면 시간은 좀 더 오래걸릴 수 있지만, 메모리를 아낄 수 있다.
반대로 재귀문을 사용하면 메모리는 더 사용되지만, 시간을 아낄 수 있다.
재귀문
const input = 주어진 값
const getFactorial = (n) => {
if (n <= 1) return 1;
return n * getFactorial(n - 1);
};
for문
const getFactorial = (x) => {
let result = 1;
for (let i = 1; i <= x; i++) {
result *= i;
}
return result;
};
전체코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const input = parseInt( | |
process.platform === "linux" ? fs.readFileSync("/dev/stdin").toString() : `10` | |
); | |
const getFactorial = (x) => { | |
let result = 1; | |
for (let i = 1; i <= x; i++) { | |
result *= i; | |
} | |
return result; | |
}; | |
console.log(getFactorial(input)); |
반응형