mrugesh 22afc2a0ca feat(learn): python certification projects (#38216)
Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
Co-authored-by: Kristofer Koishigawa <scissorsneedfoodtoo@gmail.com>
Co-authored-by: Beau Carnes <beaucarnes@gmail.com>
2020-05-27 13:19:08 +05:30

1.4 KiB

title, id, challengeType, isHidden, forumTopicId
title id challengeType isHidden forumTopicId
Fibonacci sequence 597f24c1dda4e70f53c79c81 5 false 302268

Description

Write a function to generate the nth Fibonacci number. The nth Fibonacci number is given by: Fn = Fn-1 + Fn-2 The first two terms of the series are 0 and 1. Hence, the series is: 0, 1, 1, 2, 3, 5, 8, 13...

Instructions

Tests

tests:
  - text: <code>fibonacci</code> should be a function.
    testString: assert(typeof fibonacci === 'function');
  - text: <code>fibonacci(2)</code> should return a number.
    testString: assert(typeof fibonacci(2) == 'number');
  - text: <code>fibonacci(3)</code> should return 2.
    testString: assert.equal(fibonacci(3),2);
  - text: <code>fibonacci(5)</code> should return 5.
    testString: assert.equal(fibonacci(5),5);
  - text: <code>fibonacci(10)</code> should return 55.
    testString: assert.equal(fibonacci(10),55);

Challenge Seed

function fibonacci(n) {
  // Good luck!
}

Solution

function fibonacci(n) {
  let a = 0, b = 1, t;
  while (--n >= 0) {
    t = a;
    a = b;
    b += t;
  }
  return a;
}