Added asserts for input validation.
Changed all int types to double
Reduced complexity by using floor() instead... test cases are still passing. (but there is some floating-point voodoo happening)
Added cout for future use.
#include <cmath> #include <cassert> #include <iomanip> double custom_sqrt( double a, int accuracy=20 ) { assert( 0 <= a ); assert( 0 <= accuracy ); assert( 307 >= accuracy ); // evidently, values larger than 307 cause overflow const double ACC = std::pow( 10.0, accuracy ); double result = sqrt( a ); result *= ACC; result = std::floor( result ); result /= ACC; //std::cout << std::setprecision(21) << result << std::endl; assert( 0 <= result ); return result; }
#include <math.h>- #include <cmath>
- #include <cassert>
- #include <iomanip>
double custom_sqrt (int a,int accuracy=20) {double fIntegerPart;double fFloatingPart = modf((double)sqrt(a), &fIntegerPart);double fTempFloat = fFloatingPart * pow(10, accuracy);double fTempInt;fTempFloat = modf(fTempFloat, &fTempInt);fTempFloat /= pow(10, accuracy);fFloatingPart -= fTempFloat;return fIntegerPart+fFloatingPart;- double custom_sqrt( double a, int accuracy=20 ) {
- assert( 0 <= a );
- assert( 0 <= accuracy );
- assert( 307 >= accuracy ); // evidently, values larger than 307 cause overflow
- const double ACC = std::pow( 10.0, accuracy );
- double result = sqrt( a );
- result *= ACC;
- result = std::floor( result );
- result /= ACC;
- //std::cout << std::setprecision(21) << result << std::endl;
- assert( 0 <= result );
- return result;
- }
// TODO: Replace examples and use TDD development by writing your own tests Describe(square_root) { It(should_take_square_root) { Assert::That(custom_sqrt(4), Equals(2)); Assert::That(custom_sqrt(16), Equals(4)); Assert::That(custom_sqrt(169), Equals(13)); Assert::That(custom_sqrt(8, 2), Equals(2.82)); Assert::That(custom_sqrt(8, 5), Equals(2.82842)); Assert::That(custom_sqrt(2, 11), Equals(1.41421356237)); Assert::That(custom_sqrt(2), Equals(1.41421356237309514547)); } };
- // TODO: Replace examples and use TDD development by writing your own tests
- Describe(square_root)
- {
- It(should_take_square_root)
- {
- Assert::That(custom_sqrt(4), Equals(2));
- Assert::That(custom_sqrt(16), Equals(4));
- Assert::That(custom_sqrt(169), Equals(13));
- Assert::That(custom_sqrt(8, 2), Equals(2.82));
- Assert::That(custom_sqrt(8, 5), Equals(2.82842));
- Assert::That(custom_sqrt(2, 11), Equals(1.41421356237));
- Assert::That(custom_sqrt(2), Equals(1.41421356237309514547));
- }
- };