Last active
December 15, 2015 08:29
-
-
Save sergejusb/5231188 to your computer and use it in GitHub Desktop.
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
namespace BeBetterDeveloper.Algorithms.Math | |
{ | |
using System; | |
using NUnit.Framework; | |
public static class Power | |
{ | |
public static double Pow(double number, int exp) | |
{ | |
if (number == 0 && exp < 0) throw new Exception("negative exponent for zero"); | |
if (exp == 0) return 1; | |
bool positive = true; | |
if (exp < 0) | |
{ | |
positive = false; | |
exp *= -1; | |
} | |
double result = 1; | |
while (exp >= 1) | |
{ | |
if (exp % 2 != 0) | |
{ | |
result *= number; | |
} | |
number *= number; | |
exp >>= 1; | |
} | |
return positive ? result : 1 / result; | |
} | |
} | |
[TestFixture] | |
public class PowerTests | |
{ | |
[Test] | |
[TestCase(0, 0, 1)] | |
[TestCase(0, 1, 0)] | |
[TestCase(1, 2, 1)] | |
[TestCase(2, 2, 4)] | |
[TestCase(2, 3, 8)] | |
[TestCase(2.5, 5, 97.65625)] | |
[TestCase(5, -2, 0.04)] | |
[TestCase(-2, 2, 4)] | |
[TestCase(-2, 3, -8)] | |
[TestCase(-2.5, 5, -97.65625)] | |
public void Correctly_Raises_Double_To_Power(double number, int exp, double result) | |
{ | |
var actual = Power.Pow(number, exp); | |
Assert.That(actual, Is.EqualTo(result)); | |
} | |
} | |
} |
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
namespace BeBetterDeveloper.Algorithms.Math | |
{ | |
using System; | |
using NUnit.Framework; | |
public static class PowerNaive | |
{ | |
public static double Pow(double number, int exp) | |
{ | |
if (number == 0 && exp < 0) throw new Exception("negative exponent for zero"); | |
if (exp == 0) return 1; | |
bool positive = true; | |
if (exp < 0) | |
{ | |
positive = false; | |
exp *= -1; | |
} | |
double result = 1; | |
for (int i = 1; i <= exp; i++) | |
{ | |
result *= number; | |
} | |
return positive ? result : 1 / result; | |
} | |
} | |
[TestFixture] | |
public class PowerNaiveTests | |
{ | |
[Test] | |
[TestCase(0, 0, 1)] | |
[TestCase(0, 1, 0)] | |
[TestCase(1, 2, 1)] | |
[TestCase(2, 2, 4)] | |
[TestCase(2, 3, 8)] | |
[TestCase(2.5, 5, 97.65625)] | |
[TestCase(5, -2, 0.04)] | |
[TestCase(-2, 2, 4)] | |
[TestCase(-2, 3, -8)] | |
[TestCase(-2.5, 5, -97.65625)] | |
public void Correctly_Raises_Double_To_Power(double number, int exp, double result) | |
{ | |
var actual = PowerNaive.Pow(number, exp); | |
Assert.That(actual, Is.EqualTo(result)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment