Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

algorithm - Modulo of Division of Two Numbers

we know that

(A + B) % P = (A % P + B % P) % P
(A * B) % P = (A % P * B % P) % P

where P is a prime .

I need to calculate (A / B) % P where A,B can be very large and can overflow .

Does such kind of formula for modular arithmetic holds for (A / B) % P and (A - B) % P.

If not then please explain what the correct answer is.

I.e is it true that (A / B) % P = ((A % P) / (B % P)) % P?

I WAS TRYING TO CALULATE (N*(N^2+5)/6)%P where N can be as large as 10^15

here A=n*(n^2+5) can surely overflow for n=10^15

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, but it's different:

(a - b) mod p = ((a mod p - b mod p) + p) mod p

(a / b) mod p = ((a mod p) * (b^(-1) mod p)) mod p

Where b^(-1) mod p is the modular inverse of b mod p. For p = prime, b^(-1) mod p = b^(p - 2) mod p.

Edit:

(N*(N^2+5)/6)%P

You don't need any modular inverses from this. Just simplify the fraction: N or N^2+5 will be divisible by 2 and 3. So divide them and then you have (a*b) mod P.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...