I know the algorithm finding $ (a^b) mod\;n $ avoiding large numbers so I can code it, but I'm wondering if anyone can help me with a similar algorithm for $$ (a\cdot b^c )mod\;n $$ It's quite hard to search for. I'd like to code it in C++ so not storing numbers bigger than $2^{64}$. I'd be using values of $a,b$ and $c$ between 10 and 100, if that's useful?
Asked
Active
Viewed 243 times
0
-
4What is wrong with doing the $b^c$ the way you know, then multiplying by $a$? – Ross Millikan Nov 13 '19 at 00:03
-
Because $a\cdot b^c$ is greater than $2^{64}$ and can't be held in a C++ data type without losing precision. I've switched the brackets in my question, I think it was incorrect before. – Weaver Nov 13 '19 at 00:27
-
what about using bigint arithmetic ? what's n going to be ? – Nov 13 '19 at 00:36
-
https://math.stackexchange.com/questions/81228/how-do-i-compute-ab-bmod-c-by-hand/3122918#3122918 and https://math.stackexchange.com/questions/3152587/largest-multiple-of-7-lower-than-some-78-digit-number/3152669#3152669 may help. – Nov 13 '19 at 00:45
-
1@William - I think Ross meant calculating $(b^c)\text{ mod }n$ the way you know, and then multiplying $(a\cdot(b^c\text{ mod }n))\text{ mod }n$. – mr_e_man Nov 14 '19 at 02:35
-
@mr_e_man - Ah, missed that I'll take a look. – Weaver Nov 14 '19 at 14:33
2 Answers
1
You want the method of squaring and multiplying, remembering that you can reduce modulo $n$ after every multiplication (or squaring). You never need a number bigger than $n^2$ at any stage, so your storage restrictions are no hindrance.

Lubin
- 62,818
-
Technically, you can do it so that you never get above $n^2\over 4$; using additive inverses when over half of $n$ – Nov 14 '19 at 13:08
-
0
A few things come to mind:
- additive inverses of two remainders, have the same product.
- multiplicative inverses of two remainders, multiply to the multiplicative inverse of the product.
- reducing $c$ mod $\varphi(n)$ .
- additive inverse raised to an odd exponent, is the additive inverse of the original power.
- additive inverse raised to an even exponent, is the same as the original power.
- Chinese remainder theorem.
- Polynomial remainder theorem.
- GCD reduction.
- Euler's totient theorem
- Probably a few others I've missed.
-
examples include $9\cdot 8\equiv 5\cdot 6 \pmod {14}$ for the additive inverse rule, and $11\cdot 5\equiv 9\cdot 3\pmod {14}$ for the multiplicative inverse rule . – Nov 14 '19 at 13:22