All topics
137

Computing with numbers too big to hold

Tier 1Locked

Where it runs

1. The problem

Some answers are huge. The number of ways to put 100 items in order has 158 digits. The number 21000 has more than 300 digits. A normal integer holds neither.

Usually nobody needs the full number. A problem says "return the answer modulo 1e9+7": give the remainder after dividing by that prime. A rolling hash of a substring works the same way: it is a big number of which you keep only the remainder. You need the remainder; the giant number it comes from never has to be stored.

The trap: compute the whole thing first and take the remainder at the end. In JavaScript, integers above 253 - 1 are stored inexactly, and no error tells you so. By the time of the final % m, the value is already wrong.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

Recognise it

Math and number theory (GCD, sieve, modular)

Say these words and it is this pattern

  • reduce a fraction to lowest terms
  • list all primes up to n
  • answer modulo 1e9+7
  • when do two repeating intervals line up again (LCM)

Looks similar, isn't

  • Bit manipulation

    Both work on the number itself. That page is about the individual bits.

  • Hash set / map

    A set of primes still has to be built somehow. A sieve is how you build it.

  • Dynamic programming (1-D)

    A formula answers at once where DP fills a table. Look for a closed form first.

  • Prefix sums

    Prefix sums answer over values that were stored. Here the answer comes from the numbers themselves.

GCD costs O(log of the smaller value). A sieve up to 1e7 is fine, but 1e9 is not.

On LeetCode

Counting problems that say to return the answer modulo 10^9 + 7. Take the remainder after every add and multiply, and do the multiply in BigInt, since two remainders near 10^9 multiply past 2^53.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy