Emmanuel Akinfulubi

JavaScriptMath

Fibonacci numbers and MAX_SAFE_INTEGER in JavaScript

Advanced · 4 min read

The Fibonacci numbers start 0, 1, and then each new number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. They grow fast. By the 79th one, JavaScript's ordinary numbers can no longer hold them exactly, and the answer comes out wrong by 1 with no warning at all.

In this tutorial you will generate Fibonacci numbers with a loop and two variables, find the exact point where they stop being safe, and see what the first wrong answer looks like. Then you will try a famous formula that skips the loop, find where it goes wrong (earlier!), and switch to BigInt to go all the way to the 300th. You need to know for loops and what a function is.

Safe integers

A JavaScript number is stored in 64 bits, and only 53 of those bits hold the digits. That means every whole number up to 2 ** 53 - 1 (9007199254740991) is stored exactly. These are the safe integers, and Number.isSafeInteger tells you whether a value is one of them.

JavaScript

console.log(Number.MAX_SAFE_INTEGER);       // 9007199254740991
console.log(2 ** 53 === 2 ** 53 + 1);       // true

Past that limit, there are gaps between the numbers a double can store. 2 ** 53 + 1 can't be stored, so it rounds to 2 ** 53, and the comparison says they are equal.

BigInt

A BigInt is a whole number with no size limit. You write one with an n on the end: 10n, 0n. BigInts only mix with other BigInts, so 1n + 1 is an error, but 1n + 1n is 2n.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

103 Fibonacci by iteration, and the exact moment it goes wrong

hard

Generate Fibonacci numbers with a loop and two variables. Find the last one that is a safe integer, show what the next one comes out as against its true value, and check Binet's closed form against the loop to see where it starts disagreeing. Then take the BigInt version out to F(300).

Stuck? Three hints, smallest first
  1. 1. Two variables and a swap. No array, no recursion.
  2. 2. The safe integer limit is 2 ** 53 - 1, and Fibonacci passes it somewhere in the high seventies.
  3. 3. Binet: Math.round(PHI ** n / Math.sqrt(5)). It is exact for a while and then it is not.

Step 1: two variables and a loop

Step 1

const fib = (n) => {
  let a = 0;
  let b = 1;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
};
console.log(Array.from({ length: 10 }, (unused, i) => fib(i)).join(' ')); // 0 1 1 2 3 5 8 13 21 34
console.log(fib(10), fib(30), fib(50)); // 55 832040 12586269025

a and b always hold two neighbors in the sequence. Each turn of the loop moves both one place along: a takes b's value, and b takes the sum. After n turns, a is the nth Fibonacci number, counting fib(0) as 0.

There is no array and no recursion. The loop visits each number once, so fib(1000) is just a thousand additions.

Step 2: the wrong turn, recursion

You may have seen this shorter version:

Step 2

const slowFib = (n) => (n < 2 ? n : slowFib(n - 1) + slowFib(n - 2));
console.log(slowFib(20)); // 6765

It is correct, but slowFib(20) runs the function 21,891 times, because slowFib(18) is worked out once for n - 1 and again for n - 2, and the same repeats all the way down. The number of calls roughly doubles with each extra n, so around 40 it becomes painfully slow. The two-variable loop doesn't have this problem.

Step 3: find the last safe one

Step 3

console.log(fib(78), Number.isSafeInteger(fib(78))); // 8944394323791464 true
console.log(fib(79), Number.isSafeInteger(fib(79))); // 14472334024676220 false

F(78) is inside the safe range. F(79) is past 2 ** 53, where a double can only store even whole numbers. Is 14472334024676220 the right answer? It looks fine. You can't tell by looking.

Step 4: the BigInt version tells the truth

Step 4

const fibBig = (n) => {
  let a = 0n;
  let b = 1n;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
};
console.log(String(fibBig(79))); // 14472334024676221

The loop is identical, with 0n and 1n as the starting values. The true F(79) ends in 221, not 220. The ordinary version is off by 1, and every number after it inherits the error. String(...) turns the BigInt into plain digits for printing.

Step 5: Binet's formula

There is a formula that gives the nth Fibonacci number with no loop. It uses the golden ratio, PHI, about 1.618:

Step 5

const PHI = (1 + Math.sqrt(5)) / 2;
const binet = (n) => Math.round(PHI ** n / Math.sqrt(5));
console.log(binet(10), binet(70) === fib(70)); // 55 true
console.log(binet(71), fib(71));               // 308061521170130 308061521170129

It is right all the way to F(70), then it is off by one at F(71), eight terms before the loop has any trouble. The problem is PHI itself. It goes on forever after the decimal point, but a double keeps only about 16 digits of it. Raising it to the 71st power multiplies that tiny error until rounding can no longer hide it.

Step 6: neighbors close in on PHI

Step 6

console.log(fib(50) / fib(49) === PHI); // true

Divide a Fibonacci number by the one before it and you get closer and closer to PHI. By F(50) / F(49), the result is the same double as PHI.

Step 7: go big

Step 7

const f300 = String(fibBig(300));
console.log(f300.length, f300.slice(0, 10)); // 63 2222322446

F(300) has 63 digits, and with BigInt every one of them is right.

The full solution

The answer panel has fib, fibBig and binet, and prints the first ten, the safe limit, the first wrong value, F(300), the ratio and one more pattern: every third Fibonacci number is even. Press Run to see the output.

The answer

const add = (a, b) => a + b;

const fib = (n) => {
  let a = 0;
  let b = 1;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
};

const fibBig = (n) => {
  let a = 0n;
  let b = 1n;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
};

const PHI = (1 + Math.sqrt(5)) / 2;
const binet = (n) => Math.round(PHI ** n / Math.sqrt(5));

const firstTen = Array.from({ length: 10 }, (unused, i) => fib(i));

console.log('the first ten  :', firstTen);
console.log('F(10), F(30)   :', fib(10), fib(30), 'F(50):', fib(50));
console.log('F(78)          :', fib(78), 'safe:', Number.isSafeInteger(fib(78)));
console.log('F(79) by loop  :', fib(79), 'safe:', Number.isSafeInteger(fib(79)));
console.log('F(79) truly    :', String(fibBig(79)));
console.log('Binet at 70, 71:', binet(70), binet(71), 'against', fib(70), fib(71));
console.log('F(300)         :', String(fibBig(300)));
console.log('ratio to PHI   :', fib(30) / fib(29), fib(50) / fib(49), PHI);
console.log('the identity   :', fib(10) ** 2 + fib(11) ** 2, 'should be F(21) =', fib(21));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the first ten, counting F(0) as 0', firstTen, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]);
test('F(10) is 55, F(30) is 832040 and F(50) is 12586269025', [fib(10), fib(30), fib(50)], [55, 832040, 12586269025]);
test('F(78) is the last Fibonacci number that is a safe integer', [fib(78), Number.isSafeInteger(fib(78)), Number.isSafeInteger(fib(79))], [8944394323791464, true, false]);
test('and F(79) is where the loop goes wrong: it ends in 220, not 221', [fib(79), String(fibBig(79))], [14472334024676220, '14472334024676221']);
test('Binet agrees with the loop up to F(70) and misses F(71) by one', [binet(70) === fib(70), binet(71), fib(71)], [true, 308061521170130, 308061521170129]);
test('the BigInt version reaches F(300), all sixty-three digits of it', [String(fibBig(300)).length, String(fibBig(300)).slice(0, 10)], [63, '2222322446']);
test('consecutive ratios close on the golden ratio, and by F(50) land on it exactly', [Math.abs(fib(30) / fib(29) - PHI) < 1e-11, fib(50) / fib(49) === PHI], [true, true]);
test('every third Fibonacci number is even, starting from F(0)', Array.from({ length: 9 }, (unused, i) => fib(i) % 2 === 0), [true, false, false, true, false, false, true, false, false]);
test('and F(n) squared plus F(n+1) squared is F(2n+1), while everything is safe', [fib(10) ** 2 + fib(11) ** 2, fib(21)], [10946, 10946]);

Two variables and a loop is the whole algorithm, and it is linear. The naive recursion fib(n - 1) + fib(n - 2) recomputes the same subproblems exponentially many times and is unusable past about 40; there is nothing to memoise here because iteration already visits each value once.

The interesting part is where it stops being right. F(78) is 8944394323791464, safely inside the exact integer range. F(79) should be 14472334024676221 and the loop returns 14472334024676220 — off by one, silently, because the addition landed one step past 2 ** 53 where only even integers exist. Every value after that is wrong too, and nothing in the output looks unusual. BigInt has no such wall: fibBig(300) is a 63-digit integer and every digit of it is right.

Binet's closed form is the cautionary tale. Math.round(PHI ** n / Math.sqrt(5)) is exact for a surprisingly long time — every value up to F(70) — and then quietly starts being off by one at F(71), a full eight terms before the integer range runs out. The error is in PHI itself: it is an irrational number stored in 53 bits, and raising it to the 71st power amplifies that tiny error past the point where rounding can hide it. A formula that is right for seventy cases and wrong for the seventy-first is far more dangerous than one that is obviously wrong from the start.

Common mistakes

  • Trusting numbers past 2 ** 53. Nothing throws and nothing looks odd. Check with Number.isSafeInteger, or use BigInt from the start.
  • Using a closed-form formula because it looks clever. Binet's formula fails earlier than the plain loop.
  • Mixing BigInt and Number. fibBig(10) + 1 throws a TypeError. Write fibBig(10) + 1n.

Try it yourself

  1. Find the first Fibonacci number with more than 100 digits. Which index is it?
  2. Check that F(10) squared plus F(11) squared equals F(21).
  3. Write fibList(n) that returns the first n Fibonacci numbers as an array, using the same two variables.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.