Write a function f(a,b,c) that calculates a^b (mod c) in less than 10 seconds.
- a, b < 10^100
- c < 10000.
f(10^50, 10^50, 54123) = 46555 f(5^99, 10^99, 777) = 1
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.Sign up to join this community
In GNU dc, there is the operator
|, doing exactly this. Quoted from the manual:
|Pops three values and computes a modular exponentiation. The first value popped is used as the reduction modulus; this value must be a non-zero number, and should be an integer. The second popped is used as the exponent; this value must be a non-negative number, and any fractional part of this exponent will be ignored. The third value popped is the base which gets exponentiated, which should be an integer. For small integers this is like the sequence Sm^Lm%, but, unlike ^, this command will work with arbitrarily large exponents.
You may assign it to "function" as following:
(also 5 chars...) This assigns
f. You may call it like
You can assign the function name to a variable for 11 bytes:
bcpowmod requires libbcmath, which is built into PHP since version 4.0.4, but only enabled by default on Windows. On Linux you have to explicitly configure PHP with