Skip to content

Instantly share code, notes, and snippets.

@davidjpfeiffer
Last active April 5, 2018 22:58
Show Gist options
  • Save davidjpfeiffer/e6a62d1c7ec1ad1638729b1965f7ed6b to your computer and use it in GitHub Desktop.
Save davidjpfeiffer/e6a62d1c7ec1ad1638729b1965f7ed6b to your computer and use it in GitHub Desktop.
C++ Square and Multiply Algorithm
/*
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