Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Last active April 17, 2017 08:01
Show Gist options
  • Save arman-hpp/d6d5b696b10f4b179904b93fc91bcb0c to your computer and use it in GitHub Desktop.
Save arman-hpp/d6d5b696b10f4b179904b93fc91bcb0c to your computer and use it in GitHub Desktop.
Pow with overflow
public static int Sqr(double x, double y)
{
try
{
checked
{
return (int)Math.Pow(x, y);
}
}
catch (OverflowException)
{
var overflowedResult = Math.Pow(x, y);
var t = overflowedResult / int.MinValue;
if ((int) (t % 2) != 0)
{
return int.MinValue + (int) (overflowedResult % int.MinValue);
}
return (int)(overflowedResult % int.MinValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment