### Problem: Write a function which returns the square root of an integer. Return an integer which is the floor of the integer closest to the value. Implement an algorithm with efficiency better than O(sqrt(n))

int sqrtFlr(int x) {...}

In the last post, we implemented a solution to this problem, which was O(log(n)).

The solution was:

1. Create a ceiling and floor, where the floor is 0 and the ceiling is the number.

2. Try the square of halfway between the ceiling and floor.

3. Adjust the ceiling or floor based up on the result.

4. Continue 2 and 3 and return the floor when the ceiling is one more than the floor.

Now, let's implement this is code:

int sqrtFlr(int x) {

int floor = 0;

int ceiling = x;

int halfway;

while (floor != (ceiling - 1)) {

halfway = floor + (ceiling - floor) / 2);

if ((halfway * halfway) > x) { // halfway is the ceiling!

ceiling = halfway;

} else if ((halfway * halfway < x)) {//halfway is the floor!

floor = halfway;

else { //we have a perfect square

return halfway;

}

return floor;

}

Let's try an example now, say 284.

When we start:

floor = 0

celing = 284.

we enter the while loop.

Now, halfway is 142.

142^2 is much bigger than 284, so we get:

floor = 0;

ceiling = 142

continuing through the while loop:

floor = 0;

ceiling = 142;

halfway = 71;

71^2 is still much bigger than 284, so we get:

floor = 0;

ceiling = 71;

staying in the while loop, we continue:

floor = 0;

ceiling = 71;

halfway = 35; (35^2 is much bigger still)

Now, let's implement this is code:

int sqrtFlr(int x) {

int floor = 0;

int ceiling = x;

int halfway;

while (floor != (ceiling - 1)) {

halfway = floor + (ceiling - floor) / 2);

if ((halfway * halfway) > x) { // halfway is the ceiling!

ceiling = halfway;

} else if ((halfway * halfway < x)) {//halfway is the floor!

floor = halfway;

else { //we have a perfect square

return halfway;

}

return floor;

}

Let's try an example now, say 284.

When we start:

floor = 0

celing = 284.

we enter the while loop.

Now, halfway is 142.

142^2 is much bigger than 284, so we get:

floor = 0;

ceiling = 142

continuing through the while loop:

floor = 0;

ceiling = 142;

halfway = 71;

71^2 is still much bigger than 284, so we get:

floor = 0;

ceiling = 71;

staying in the while loop, we continue:

floor = 0;

ceiling = 71;

halfway = 35; (35^2 is much bigger still)

staying in the while loop, we continue:

floor = 0;

ceiling = 35;

halfway = 17; (17^2 is much bigger still)

staying in the while loop, we continue:

floor = 0;

ceiling = 17;

halfway = 8; (8^2 = 64, which is smaller)

staying in the while loop, we continue:

floor = 8;

ceiling = 17;

halfway = 12; (12^2 = 144, which is smaller)

staying in the while loop, we continue:

floor = 15;

ceiling = 17;

halfway = 16; (16^2 = 256, which is smaller) and we set floor to 16.

Now, when we go to the while loop, it fails and we fall out, and return 16.

16 is the correct answer here.

So, this solution seems to work.

Let's think of edge cases here. Try a perfect square, say 16.

floor = 0;

ceiling = 16;

halfway = 8; (8^2 = 64, which is larger).

Continuing through the for loop:

floor = 0;

ceiling = 8;

halfway = 4; (4^2 = 16, which is equal, trigger the else in the if statement, and returns true, so this works).

And there is is. An O(log n) solution to returning square root floor!

floor = 0;

ceiling = 35;

halfway = 17; (17^2 is much bigger still)

staying in the while loop, we continue:

floor = 0;

ceiling = 17;

halfway = 8; (8^2 = 64, which is smaller)

staying in the while loop, we continue:

floor = 8;

ceiling = 17;

halfway = 12; (12^2 = 144, which is smaller)

staying in the while loop, we continue:

floor = 12;

ceiling = 17;

halfway = 14; (14^2 = 196, which is smaller)

floor = 12;

ceiling = 17;

halfway = 14; (14^2 = 196, which is smaller)

staying in the while loop, we continue:

floor = 14;

ceiling = 17;

halfway = 15; (15^2 = 225, which is smaller)

floor = 14;

ceiling = 17;

halfway = 15; (15^2 = 225, which is smaller)

floor = 15;

ceiling = 17;

halfway = 16; (16^2 = 256, which is smaller) and we set floor to 16.

Now, when we go to the while loop, it fails and we fall out, and return 16.

16 is the correct answer here.

So, this solution seems to work.

Let's think of edge cases here. Try a perfect square, say 16.

floor = 0;

ceiling = 16;

halfway = 8; (8^2 = 64, which is larger).

Continuing through the for loop:

floor = 0;

ceiling = 8;

halfway = 4; (4^2 = 16, which is equal, trigger the else in the if statement, and returns true, so this works).

Ok-- any edge cases. Well, we could try 0 and 1, and this works. How about negative numbers. Well, let's return -1 in this case, and then we're done.

int sqrtFlr(int x) {

int floor = 0;

int ceiling = x;

int halfway;

if (x < 0) return -1; //error case.

while (floor != (ceiling - 1)) {

halfway = floor + (ceiling - floor) / 2);

if ((halfway * halfway) > x) { // halfway is the ceiling!

ceiling = halfway;

} else if ((halfway * halfway < x)) {//halfway is the floor!

floor = halfway;

else { //we have a perfect square

return halfway;

}

return floor;

}

int floor = 0;

int ceiling = x;

int halfway;

if (x < 0) return -1; //error case.

while (floor != (ceiling - 1)) {

halfway = floor + (ceiling - floor) / 2);

if ((halfway * halfway) > x) { // halfway is the ceiling!

ceiling = halfway;

} else if ((halfway * halfway < x)) {//halfway is the floor!

floor = halfway;

else { //we have a perfect square

return halfway;

}

return floor;

}

And there is is. An O(log n) solution to returning square root floor!

/* Please send along any bugs or optimizations! */

Nice! In computer science, we'd say this problem can be "reduced" to a Binary Search problem. Meaning, they're equivalent.

ReplyDeleteVery nice pick-up! Thanks Amin.

DeleteNice, but doesn't work for x = 1, does it? It'll never enter the loop (because the floor is initially already one less than the ceiling), hence returning the initial floor, i.e. 0 ... so do we just make 1 a special case too?

ReplyDeleteNice catch Amir! I just noticed that very same flaw in my own solution

DeleteI noticed that if x is larger than 100,000, then there is an overflow issue, so I am thinking is there a way to lower down that upperbound first....

ReplyDeleteWatch your favourtie pinoy channel replays and all the pinoy flix tv tambyan replays online in hd.

ReplyDeleteGet your favourite Filipino tv shows online and all Teleserye Pinoy Channel Tv Get videos and download all Pinoy tv

ReplyDeleteAwesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work! Please visit webstagram

ReplyDeleteBagi para penggemar yang ingin bermain Slot Online Deposit Pulsa Tanpa Potongan yang bisa dimainkan dengan sangat mudah dan dimanapun kapanpun kalian inginkan bisa langsung mengunjungi situs IDN89 yang sudah terpercaya melalui https://188.166.252.208/

ReplyDeletePinoy Channele bringing you best videos from all over Filipino entertainment, sports,

ReplyDeletenews, politics, technology, music, covering all Latest Tv Replay Show of Pinoy Teleserye.

Marry Me, Marry You

Dance + Season 6: Latest & Full Episodes of Dance + online on Disney+ Hotstar.

ReplyDeleteBinge watch episodes of Dance + entire season 6 only on Disney+ Hotstar.

Molkki

Today's episode starts with Kanta getting emotional. Anuj asks Kanta

ReplyDeletewhat happened. Devika asks Kanta if she said anything wrong. Anupama asks

Anupama Online

Vivian D'Sena, who was last seen on the show Shakti - Astitva Ke Ehsaas Ki,

ReplyDeleteis making a comeback to television with romantic drama Sirf Tum Hindi Serial.

Sirf Tum

Watch and download Korean drama, movies, Kshow and other Asian

ReplyDeletedramas with english subtitles online free. Dramacool for everyone!

DramaCool

Udaariyaan Serial is 2021 latest tv show of colors is the story of two sisters Jasmine and Tejo from a small pind in Punjab, and the dashing village boy Fateh.

ReplyDeleteAnupama

I got to learn a few excellent stuff here. Certainly reading bookmarking

ReplyDeletefor revisiting. I wonder how much efforts

you place here to create this such magnificent informative content site.

Naagin 6 Online

KissAsian is the best website to Korean dramas and movies online free with

ReplyDeleteEnglish Subtitles and Dubbed. This website Chris Gayle, movies of genres ...

KissAsian

[url=https://kissasian4u.com/]KissAsian[/url]

Kepala Bergetar Tonton Malasian Dramas dan Download Live Malay Telefilem, Dfm2u Malay Dramas. MyFlm4u Terkini Gempak Episode

ReplyDeleteNice Post, This is really an amazing content very helpful. It solved my issue. Thanks

ReplyDeleteWatch all the famous Korean Dramas, News and International News Here for free

https://kisasian.cc/