Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 3, 2013 03:09
Show Gist options
  • Select an option

  • Save riyadparvez/5915147 to your computer and use it in GitHub Desktop.

Select an option

Save riyadparvez/5915147 to your computer and use it in GitHub Desktop.
Implementation of exponentiation by squaring in C#. See http://en.wikipedia.org/wiki/Exponentiation_by_squaring
public static int PowerBySquaring(int baseNumber, int exponent)
{
int result = 1;
while (exponent != 0)
{
if ((exponent & 1)==1)
{
result *= baseNumber;
}
exponent >>= 1;
baseNumber *= baseNumber;
}
return result;
}
@lukakostic
Copy link

lukakostic commented Mar 10, 2019

public static double PowerBySquaring(double baseNumber, int exponent)
{
    double result = 1.0;
    while (exponent > 0)
    {
        if (exponent % 2 == 1)
            result *= baseNumber;
        exponent >>= 1;
        baseNumber *= baseNumber;
    }

    return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment