0

I would like to ask about sqrt() function in library in c++, I have an integer number and I want to know if there is an integer-square root fo this number...like 16 --> 4, and if not return -1 here is the function:

long long SQRT(Long long x)
{
    long long i;
    for (i = 0; i <= x / 2; i++)
      if (i * i == x)
        return i;
    return -1;
}

but it takes much more time than sqrt()...can any one explain me that...thanks in advance

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Your method is too straight forward and is obviously will be too slow. – MikeCAT Mar 19 '16 at 11:08
  • Check this link out: http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi. It shows several ways of implementing sqrt and running times. – Florin Petriuc Mar 19 '16 at 11:10
  • 1
    To speed up your code, you can try [Fast inverse square root](https://en.wikipedia.org/wiki/Fast_inverse_square_root) approach – Peter Szekeli Mar 19 '16 at 11:11
  • I'm flagging this question as too broad. Fast and accurate implementations of functions like these require thorough knowledge of numerical math and/or calculus. The same would go for questions about many other `` functions. –  Mar 19 '16 at 11:25
  • thanks i got the answer from your links...thanks very much – E-mad Wahid Mar 19 '16 at 14:41

0 Answers0