I want to implement my own (simple) large/arbitrary integer precision arithmetic, first in Java (cause I am more familiar with the syntax), then rewrite it to C.
I have addition, subtraction and multiplication for numbers of infinite length and now I need modulo for cryptographic applications.
I store the digits of my arbitrary numbers in an array, I followed the following guide on how to store the numbers: How to handle very large numbers in Java without using java.math.BigInteger
So for example I want to calculate
849465603662254214335539562 % 578907659710377778063722
when I have two arrays:
int[] a = [8, 4, 9, 4, 6, 5, 6, 0, 3, 6, 6, 2, 2, 5, 4, 2, 1, 4, 3, 3, 5, 5, 3, 9, 5, 6, 2]
int[] b = [5, 7, 8, 9, 0, 7, 6, 5, 9, 7, 1, 0, 3, 7, 7, 7, 7, 8, 0, 6, 3, 7, 2, 2]
representing those numbers.
What would be a simple as possible solution to get
int[] c = modFunction(a, b)
Any help is appreciated.
Method 1
I came up with this method; it's not necessarily efficient, but it works.
Notice that you can use the length of the input (in digits) to compute its logarithm.
You can use this to perform division, and therefore modulus.
Specifically, first notice that
Therefore
Now notice that
Therefore
Now notice that
Therefore
And finally, notice that
Therefore
So the answer is
208066867130013916059388
.The powers of 10 are easy to obtain just by examining the length, and you can figure out which multiple of them you need to subtract by just trying out all 10 possibilities with multiplication and figuring out which is the highest that gives a nonnegative result.
Method 2
Just binary search for the quotient using multiplication! Then find the remainder using the quotient.