fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int mySqrt(int x) {
  5. if(x <= 1){
  6. return x;
  7. }
  8. int low = 0, high = x / 2;
  9. //long to prevent overflow
  10. long long mid;
  11. while(low <= high){
  12. mid = (low + high) / 2;
  13. //needs to be long to prevent overflow
  14. long long t = mid * mid;
  15. //second part is to return floor if x is not perfect square
  16. if( t == x || ((t < x) && ((mid + 1) * (mid + 1) > x))){
  17. break;
  18. } else if(x < t){
  19. high = mid - 1;
  20. }else{
  21. low = mid + 1;
  22. }
  23. }
  24. return mid;
  25. }
  26.  
  27. int main() {
  28. cout << mySqrt(16) << endl;
  29. cout << mySqrt(27) << endl;
  30. return 0;
  31. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
4
5