Skip to content

Update binary-exp.md #1475

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed

Conversation

UtkarshSingh1923
Copy link

Distributive law of modulo over multiplication to handle overflow

Distributive law of modulo over multiplication to handle overflow
@mhayter
Copy link
Contributor

mhayter commented Jul 1, 2025

Can you give an example of where the previous code fails?

@UtkarshSingh1923
Copy link
Author

Can you give an example of where the previous code fails?

a = 3 037 000 500;
b = 2;
m = 3 037 000 501;
a * a = 3 037 000 500 × 3 037 000 500
≈ 9.223 372 037 000 025 000
which is just above LLONG_MAX = 9 223 372 036 854 775 807, so the multiplication overflows.

@mhayter
Copy link
Contributor

mhayter commented Jul 1, 2025

The same problem happens with your code: https://www.ideone.com/ZqJd1u

Typically, the assumption is M^2 fits into the data type otherwise you must expand the data type for multiplication.

@mhayter mhayter closed this Jul 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants