0

So , from what i have read on the internet , modulo can do this:

(a*b) % n = (a % n * b % n)%n;

Which i understand because a%n * b%n can be bigger than n , so we have to take modulo n again.But i don't get n! mod p.Algorithm from internet:

int result = 1;
for (int i = 1 ; i <= n ; i++)
{
   result = (result * i ) % p;
}
cout<<result;
  Let's say n = 3 , and p is 7.
When i = 1 , result = 1 % 7 ,
when i = 2 , result = (1%7 * 2) % 7 , and when i = 3 ,
result =((1%7*2) % 7 * 3) % 7.

I don't really see the connection between my first statement and this result.From what i see , for n = 2 , n! % 7 should be (1 % 7 * 2 % 7 ) % 7 , not as the algorithm would do it:(1 % 7 * 2 ) % 7. I know the algorithm is right and i am missing something...Can anyone help me?

6
  • 1
    (a*b) % n == (a%n * b) % n is also true. Commented Jan 24, 2021 at 17:16
  • @IgorTandetnik can you explain me why ? Commented Jan 24, 2021 at 17:18
  • 1
    By definition of remainder, a is representable as q*n + r where q=floor(a/n) and r=a%n. Then a*b == (q*n+r)*b == n*q*b + r*b. The first component is clearly divisible by n, so (a*b)%n == (r*b)%n == (a%n * b) %n. QED Commented Jan 24, 2021 at 17:21
  • Mathematically there all the same. Practically, a * b might overflow your integer type and (a % n) * (b % n) might not. Commented Jan 24, 2021 at 17:33
  • @cosmin-andreiparaschiv More generally if a=x mod n and b=y mod n then a*b = x*y mod n. So if a%n = x%n and b%n = y%n then (a*b)%n=(x*y)%n. Your expressions are all variations on that same theme. Commented Jan 24, 2021 at 17:45

1 Answer 1

1

Mathematically they are the same but the computer has a limited number of bits to represent numbers and if you exceed that limit you will get unexpected results.

See the following example:

Imagine the maximum value that could be stored is 200 and you wanted to compute X * Y % 100.

Lets try some values for X and Y:

  1. X = 103 and Y = 98 ==> 3 * 98 > 296 OVERFLOW
  2. X = 103 and Y = 103 ==> 3 * 3 > 9 OK

In case 2, if you take the modulus of both before multiplying, you get a result below 200. But if you only take from one variable, you would have 309 % 200, but 309 would become some twisted value since the type can only represent up to 200.

In case 1, you would have to come up with another strategy (maybe a bigger type or transform your multiplication into sums) because the result of the multiplication would extrapolate the 200 limit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.