fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. float my_sqrt(float n) {
  7. float best = 1;
  8. const float accuracy = 0.01;
  9. const float starting_step = accuracy * accuracy * accuracy;
  10. float step = starting_step;
  11. float step_diff = starting_step;
  12. int steps_no = 0;
  13. while (fabs(best*best - n) > accuracy) {
  14. if (steps_no == 10000) break;
  15. // cout << best << endl;
  16. steps_no++;
  17. if (best*best > n) {
  18. best -= step;
  19. step /= 2;
  20. step_diff = starting_step;
  21. // best -= step;
  22. // step = starting_step;
  23. // step_diff = starting_step;
  24. } else {
  25. step_diff *= 2;
  26. step += step_diff;
  27. best += step;
  28. }
  29. }
  30. cout << "in " << steps_no << " steps" << endl;
  31. return best;
  32. }
  33.  
  34. int main() {
  35. float result = my_sqrt(32100);
  36. cout << result << " ^ 2 = " << result * result << endl;
  37. return 0;
  38. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
in 68 steps
179.165 ^ 2 = 32100