알고리즘

재귀: power 제곱, factorial 계승

selonjulie 2022. 9. 3. 22:43

Write a function called power which accepts a base and an exponent. The function should return the power of the base to the exponent. This function should mimic the functionality of Math.pow()  - do not worry about negative bases and exponents.

 

베이스와 지수를 받아들이는 거듭제곱이라는 함수를 작성하십시오. 함수는 베이스의 거듭제곱을 지수로 반환해야합니다. 이 기능은 Math.pow ()의 기능을 모방해야합니다.

 

function power(base, exponent) {
  if (exponent === 0) return 1;
  return base * power(base, exponent - 1);
}

// power(2,0) // 1
// power(2,2) // 4
// power(2,4) // 16

 

 

Write a function factorial which accepts a number and returns the factorial of that number. A factorial is the product of an integer and all the integers below it; e.g., factorial four ( 4! ) is equal to 24, because 4 * 3 * 2 * 1 equals 24.  factorial zero (0!) is always 1.

 

숫자를 받아들이고 해당 숫자의 계승을 반환하는 기능 요인을 작성하십시오. 계승은 정수의 산물이며 그 아래의 모든 정수입니다. 예를 들어, Factorial Four (4!)는 24와 같으며, 4 * 3 * 2 * 1은 24와 같기 때문입니다. Factorial Zero (0!)는 항상 1입니다.

function factorial(num) {
  if (num === 1) return 1;
  return num * factorial(num - 1);
}

//factorial(1) // 1
// factorial(2) // 2
// factorial(4) // 24
// factorial(7) // 5040

'알고리즘' 카테고리의 다른 글

[재귀] someRecursive  (0) 2022.10.31
재귀: recursive range, Fib  (0) 2022.10.02
Recursion 재귀  (0) 2022.08.15
[Sliding window] minSubArrayLen  (0) 2022.08.07
알고리즘 문제풀이 접근 방법  (0) 2022.08.07