1

How can I raise large numbers to a power in python?

a = 62608558862573792084872798679396455703616395237802859621162736207631538899993
b = 93910650126758265671774994856253142403789359314618444886584691522424141933664
c = pow(a, b)

It is impossible to get an answer that way. Are there any ways to raise large numbers to a power to make it work?

jaroslaw
  • 23
  • 2
  • _It is impossible to get an answer that way_ What do you mean "impossible"? What happens when you try? – John Gordon Dec 03 '22 at 18:19
  • 2
    Could be an [X-Y Problem](https://xyproblem.info/). Why do you need it? Usually when you need huge numbers it's for cryptography and you really need `a**b % c` which `pow(a,b,c)` provides and is much faster. – Mark Tolonen Dec 03 '22 at 18:19
  • Even using a recursion algorithm for powers, this is too much. I suggest you look into the answer of @MarkTolenen. – Lexpj Dec 03 '22 at 18:22
  • @MarkTolonen I need to implement `pow(h, pow(a, b), n).to_bytes(32, 'big')` and get the answer. Am I right that `pow(h, pow(a, b, n), n).to_bytes(32, 'big')` equals `pow(h, pow(a, b), n).to_bytes(32, 'big')` ? – jaroslaw Dec 03 '22 at 18:26
  • As a general answer about the limitations of `pow()` and alternative methods, see: [Python math range error](https://stackoverflow.com/q/43148927/13843268). – sj95126 Dec 03 '22 at 18:33

1 Answers1

3

If you calculate the result to all digits, it has 10^78 digits. That's more than will fit into any RAM of any computer in the world today.

It is impossible to get an answer that way.

It will be impossible to get a precise answer for a long time, given that Earth only has ~10^50 atoms.

The number 62608558862573792084872798679396455703616395237802859621162736207631538899993 looks like a pseudo prime number (is has only 5 prime factors) as used in cryptography. Cryptography often works with modulo operations to limit the number of digits. You can use pow to do modulo math as well:

pow(base, exp, mod=None)

Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod).

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222