Last active
July 22, 2023 19:46
-
-
Save mudassaralichouhan/a89c96b2d5e38099b8cc859bdadefb0f to your computer and use it in GitHub Desktop.
SquareRoot Here is a very awesome code to find sqrt and even faster than original sqrt function.
This file contains 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
#include "iostream" | |
#define EPSILON 0.0000001 // least minimum value for comparison | |
using namespace std; | |
class Solution { | |
public: | |
int mySqrt(double x) { | |
if (x <= 0) | |
return 0; | |
double s = x; | |
while ((s - x / s) > EPSILON) | |
s = (s + x / s) / 2; | |
return static_cast<int>(s); | |
} | |
}; | |
int main() | |
{ | |
Solution solution; | |
cout << solution.mySqrt(4) << std::endl; | |
cout << solution.mySqrt(64) << std::endl; | |
cout << solution.mySqrt(994009) << std::endl; | |
cout << solution.mySqrt(996004) << std::endl; | |
cout << solution.mySqrt(998001) << std::endl; | |
cout << solution.mySqrt(1000000) << std::endl; | |
cout << solution.mySqrt(2147483647) << std::endl; | |
return 0; | |
} |
This file contains 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
float InvSqrt (float x) | |
{ | |
float xhalf = 0.5f*x; | |
int i = *(int*)&x; | |
i = 0x5f375a86 - (i>>1); | |
x = *(float*)&i; | |
x = x*(1.5f - xhalf*x*x); | |
x = x*(1.5f - xhalf*x*x); | |
x = x*(1.5f - xhalf*x*x); | |
x=1/x; | |
return x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Finding square root without using sqrt function?