반응형

피보나치 수 문제를 풀어보았다

팩토리얼과 마찬가지로

기본적인 재귀함수 구현에 대한 문제였다.

 

피보나치 수는

F0 = 0;

F1 = 1;

Fn = F(n-1) + F(n-2) 라는 공식이 있다.

 

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().split(" ");
const value = parseInt(input[0]);

function fibonacci(m, n, arr) {
  const a = arr[0];
  const b = arr[1];

  if (m > n) {
    console.log(b);
  } else {
    const newArr = [b, a + b];
    const _m = m + 1;
    fibonacci(_m, n, newArr);
  }
}

if (value === 0) {
  console.log(0);
} else if (value === 1) {
  console.log(1);
} else {
  fibonacci(2, value, [0, 1]);
}
반응형
반응형

재귀의 가장 기본이라고 할수있는

팩토리얼 문제를 풀어보았다.

 

팩토리얼이란

주어진 수 까지의 차례곱을 의미한다.

 

예) 5! = 1 * 2 * 3 * 4 * 5 = 120

 

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().split(" ");
const value = parseInt(input[0]);

function factorial(n, sum) {
  if (n === 0) {
    console.log(sum);
  } else {
    const multi = sum * n;
    const m = n - 1;
    factorial(m, multi);
  }
}

factorial(value, 1);

 

 

https://github.com/jaekwangLee/algorithm

 

GitHub - jaekwangLee/algorithm

Contribute to jaekwangLee/algorithm development by creating an account on GitHub.

github.com

 

반응형