How do I deal with large modulus in mod function that produces a wrong result?

11 views (last 30 days)
Hi all. I'm currently doing up an assignment (RSA) that deals with encrypting and is stuck with the following problem:
I'm using the mod built-in function with large numbers.
mod(b,a)
p = randi([2^15 2^16]);
q = randi([2^15 2^16]);
a = p*q;
result = mod(b,a);
Therefore a is in the range of 2^52 where the maximum unsigned double-precision floating-point integer is 2^53-1. b is a number that undergoes SquareAndMultiply and its value increases throughout the function. Hence, when b is smaller than a, mod(b,a) will just be b. However, there will come a point when b = 2^30. The next step when b is squared, b = 2^60 which is already over the maximum 2^53-1. This is when MATLAB will cut off or round off b and mod(b,a) produces a wrong result.
Does anyone have any idea, answers or suggestions to how can I resolve this problem?
Thank you.

Answers (2)

Walter Roberson
Walter Roberson on 10 Nov 2012
Edited: Walter Roberson on 10 Nov 2012
Try working with uint64() instead of double precision.
However, if the implication of your question is that b could be derived from a number up to 2^52-1 before the square and multiply then it could potentially be somewhere over 2^104 which would be too large for uint64()

Matt Fig
Matt Fig on 10 Nov 2012
Edited: Matt Fig on 10 Nov 2012
I would say you have to go symbolic.
mod(sym(A),sym(B))

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!