All topics
136

Raising to a big power, fast

Tier 1Locked

Where it runs

1. The problem

Step 135 found primes with less work per number. This step does less work per power. You need base^exp: base multiplied by itself exp times. When exp is small, you just multiply. When exp is a million or a billion, multiplying one step at a time means a million or a billion operations.

There is a second problem. The number 21000000 has more than 300,000 digits. A normal integer cannot hold it, and you usually don't need it anyway: the problem asks for the answer modulo some number m, that is, the remainder after dividing by m. So you need base^exp mod m, with the numbers kept small the whole way and far fewer steps than exp.

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

On LeetCode

Problems that raise a number to a huge power, often with a remainder. Squaring the base and halving the exponent takes O(log n) steps where plain multiplying takes n. When the modulus is near 10^9 the squares pass 2^53, and lesson 137 shows the fix.

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