Skip to content

Instantly share code, notes, and snippets.

@mudassaralichouhan
Last active July 22, 2023 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudassaralichouhan/a89c96b2d5e38099b8cc859bdadefb0f to your computer and use it in GitHub Desktop.
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.
#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;
}
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;
}
@mudassaralichouhan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment