How to find the square root of a number in R without using any function

r

#1

Hello,

Recently I came across this interview question:
Find the square root of a number without using any inbuilt function.
Here is my code for it:

sqrt_1 <- function(n){
  for (i in 1:n-1){
    r <- i * i
    if (r <= n) x = i  
  }
  x
}

But this is good only for squares like 25,36 etc.For others it gives the previous square root.

> sqrt_1(9.1)
[1] 3

I learned that this is a basic interview question which has been asked in many interviews:
stackoverflow.Though this link gives many ways to calculate this in other languages I am looking for a solution in R.
Can someone please help me with this one?


#2

Hi @data_hacks,

Will this be counted ?

a^0.5

Or you can implement this -

sqrt_1 <- function(n){
  for (i in seq(1,4,by = 0.0000001)){
    r <- i * i
    if (r <= n) x = i  
  }
  x
}

sqrt_1(9.1)

If they see seq as a function then a do while loop can do this job :slight_smile:


#3

It depends on what they want from you. If they want to see how you think on your feet, then @aayushmnit’s methods are the way to go. It may be realizing that the square root is the number to the power 0.5 is what they want. Or they may want a loop like both of you did, with a finer grid.

Alternatively, they may want to see how you think about problems, or, alternatively, what you know. There are some ideas on Wikipedia: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots


#4

If the exponentiation operator ^ is not counted as a function then you could just use x^0.5 to find the square root of x.