Ad

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.

Code
Diff
  • #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;
    • }