-1
example

root of 1 as 1*sqrt{1}

root of 2 as 1*sqrt{2}

root of 3 as 1*sqrt{3}

root of 9 as 3*sqrt{1}

I tried to find a algorithm like below:

for(i=sqrt(n);i>=1;i--)
if(n%(i*i)==0) {
    break;
}
cout<<i<<' '<<n/(i*i)<<endl;

but it is not good when n is big number

so can you tell me a algorithm for this problem ? thank you so much!

Road Human
  • 123
  • 5
  • 1
    Please describe what you want to calculate. This is definitely not the square root. – undur_gongor Nov 17 '15 at 08:29
  • no the answers must be nature numbers – Road Human Nov 17 '15 at 08:30
  • 3
    I think what the OP wants to achieve is to extract the greatest perfect square `a*a` from under the root, so that `a` can be moved outside. `sqrt(a*a*b) == a*sqrt(b)`. It's just a simplification of the expression. – M Oehm Nov 17 '15 at 08:33
  • 1
    What is that `3*sqrt{1}` notation supposed to mean? that `sqrt(9) == 3*sqrt(1)`? Also, see http://stackoverflow.com/questions/1100090/looking-for-an-efficient-integer-square-root-algorithm-for-arm-thumb2 for an O(log n) `isqrt` (i.e. linear in the number of bits in the binary representation). – Peter Cordes Nov 17 '15 at 08:35
  • 2
    Looking at your example series, it seems that what you want to do is to *find the perfect square factors of `n`*. Perfect square factors can be moved outside of the square root as an integer. If that's the case, then please put that in the question. *square root of natural numbers* means just square root: you can calculate that with `sqrt(n)` and the result itself won't be a natural number. – eerorika Nov 17 '15 at 09:01

2 Answers2

3

What are you expecting your code to do? For a given n you're finding the largest number i whose square divides n. If n is prime, for instance (say n=5, 17, etc.) this condition can only be satisfied if i=1, so you're going to wind up with the result 1 a lot of the time.

djechlin
  • 54,898
  • 29
  • 144
  • 264
1

The question does not account for perfect/non-perfect squares. Since the square root can be a float/double, an iterative approach is a more precise way to find the root.

This link might help : https://math.stackexchange.com/questions/296102/fastest-square-root-algorithm

Community
  • 1
  • 1
user2582651
  • 73
  • 1
  • 6