Last active
April 5, 2018 22:58
-
-
Save davidjpfeiffer/e6a62d1c7ec1ad1638729b1965f7ed6b to your computer and use it in GitHub Desktop.
C++ Square and Multiply Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Square and Multiply Algorithm | |
By David J Pfeiffer | |
The below function calculates x ^ y % p while avoiding overflow for large values of x and y | |
*/ | |
int sam(int x, unsigned int y, unsigned int p) | |
{ | |
int result = 1; | |
x = x % p; | |
while (y > 0) | |
{ | |
if (y % 2 == 1) | |
{ | |
result = result * x % p; | |
} | |
y = y / 2; | |
x = x * x % p; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment