상세 컨텐츠

본문 제목

Find NthFibonacci without recursion(반복문을 이용한 n번째 피보나치 수 찾기) - Javascript

Programming/Algorithm

by 쌩우 2019. 6. 9. 00:53

본문

재귀 함수 없이 n번째 피보나치 수를 찾아라!

흔히들 피보나치 수를 찾을 때에 recursion을 이용하여 해당 숫자를 찾는다.
하지만 모든 재귀함수는 모두 반복문으로 구현이 가능하고,
모든 반복문은 모두 재귀함수로 구현이 가능하다고 한다.

그러므로 이번에는 재귀함수의 적용 없이 피보나치 수를 찾아 보았다.

/**
 * A Fibonacci sequence is a list of numbers that begins with 0 and 1, and each
 * subsequent number is the sum of the previous two.
 *
 * For example, the first five Fibonacci numbers are:
 *
 *   0 1 1 2 3
 *
 * If n were 4, your function should return 3; for 5, it should return 5.
 *
 * Write a function that accepts a number, n, and returns the nth Fibonacci
 * number. Use a recursive solution to this problem; if you finish with time
 * left over, implement an iterative solution.
 *
 * example usage:
 * nthFibonacci(2); // => 1
 * nthFibonacci(3); // => 2
 * nthFibonacci(4); // => 3
 * etc...
 *
 */

var nthFibonacci = function (n) {
  if(n === 0) {
    return 0;
  } // n이 0일땐 바로 0을 반환
  if(n === 1) {
    return 1;
  } // n이 1일땐 바로 1을 반환
  let a = 0;    //그 외에는 n이 1보다 큰 경우에 아래의 코드로 진행될 것이다.
  let b = 1;
  let c;
  let i = 1;
  while(i < n) {
    c = a + b;    //n번째 피보나치 수를 변수 c에 미리 담아 놓는다.
    a = b;        //n+1번째 피보나치 수를 찾을 때에 사용할 수도 있으니, 각각 a와 b를 이동시켜 준다.
    b = c;
    i++;
  }
  return b;        //처음에 c의 변수에 담아뒀던 값을 b에 새로 선언해주었으니, 이 때에 반환되는 값은 n번째 피보나치 수가 될 것이다.
};

관련글 더보기

댓글 영역