https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Large%20Search%20Engine%20Company%20/Search%20Engine%20Company%20-%20Interview%20Problems%20-%20SOLUTIONS/On-Site%20Question%204%20-%20SOLUTION.ipynb

On-Site Question 4 - SOLUTION

Question

Find the squareroot of a given number rounded down to the nearest integer, without using the sqrt function. For example, squareroot of a number between [9, 15] should return 3, and [16, 24] should be 4.

Requirements

Feel free to code this out (but its recommended that you use paper/pencil or whiteboard)

 

Solution

The squareroot of a (non-negative) number N always lies between 0 and N/2. The straightforward way to solve this problem would be to check every number k between 0 and N/2, until the square of k becomes greater than or rqual to N. If k^2 becomes equal to N, then we return k. Otherwise, we return k-1 because we're rounding down. Here's the code.

def solution(num):
if num<0:
raise ValueError
if num==1:
return 1
for k in range(1+(num/2)):
if k**2==num:
return k
elif k**2>num:
return k-1
return k
In [2]:
solution(14)
Out[2]:
3
In [3]:
solution(15)
Out[3]:
3
In [4]:
solution(16)
Out[4]:
4
 

The complexity of this approach is O(N), because we have to check N/2 numbers in the worst case. This linear algorithm is pretty inefficient, we can use some sort of binary search to speed it up. We know that the result is between 0 and N/2, so we can first try N/4 to see whether its square is less than, greater than, or equal to N. If it’s equal then we simply return that value. If it’s less, then we continue our search between N/4 and N/2. Otherwise if it’s greater, then we search between 0 and N/4. In both cases we reduce the potential range by half and continue, this is the logic of binary search. We’re not performing regular binary search though, it’s modified. We want to ensure that we stop at a number k, where k^2<=N but (k+1)^2>N. For example:

 
 
def better_solution(num):
if num<0:
raise ValueError
if num==1:
return 1
low=0
high=1+(num/2) while low+1<high:
mid=low+(high-low)/2
square=mid**2
if square==num:
return mid
elif square<num:
low=mid
else: high=mid return low
 
 
In [9]:
better_solution(14)
Out[9]:
3
In [10]:
better_solution(15)
Out[10]:
3
In [11]:
better_solution(16)
Out[11]:
4
 

One difference from regular binary search is the condition of the while loop, it’s low+1<high instead of low<high. Also we have low=mid instead of low=mid+1, and high=mid instead of high=mid-1. These are the modifications we make to standard binary search. The complexity is still the same though, it’s logarithmic O(logN). Which is much better than the naive linear solution.

There’s also a constant time O(1) solution which involves a clever math trick. Here it is:

 

This solution exploits the property that if we take the exponent of the log of a number, the result doesn’t change, it’s still the number itself. So we can first calculate the log of a number, multiply with 0.5, take the exponent, and finally take the floor of that value to round it down. This way we can avoid using the sqrt function by using the log function. Logarithm of a number rounded down to the nearest integer can be calculated in constant time, by looking at the position of the leftmost 1 in the binary representation of the number. For example, the number 6 in binary is 110, and the leftmost 1 is at position 2 (starting from right counting from 0). So the logarithm of 6 rounded down is 2. This solution doesn’t always give the same result as above algorithms though, because of the rounding effects. And depending on the interviewer’s perspective this approach can be regarded as either very elegant and clever, or tricky and invalid. Either way, you should let your interviewer know that you are capable of the shortcut!

 

Good Job!

Find the squareroot的更多相关文章

  1. Junit的使用

    Junit是用于编写单元测试的框架.对于已经写好的函数,可以使用Junit生成单元测试代码. 自己的环境是:Linux Java环境是:JDK1.7 IDE:Eclipse Java EE IDE f ...

  2. [转]在Eclipse中使用JUnit4进行单元测试(初级篇)

    首先,我们来一个傻瓜式速成教程,不要问为什么,Follow Me,先来体验一下单元测试的快感! 首先新建一个项目叫JUnit_Test,我们编写一个Calculator类,这是一个能够简单实现加减乘除 ...

  3. 在Eclipse中使用JUnit4进行单元测试(高级篇)

    通过前2篇文章,您一定对JUnit有了一个基本的了解,下面我们来探讨一下JUnit4中一些高级特性. 一.高级Fixture 上一篇文章中我们介绍了两个Fixture标注,分别是@Before和@Af ...

  4. 在Eclipse中使用JUnit4进行单元测试(初级篇)

    首先,我们来一个傻瓜式速成教程,不要问为什么,Follow Me,先来体验一下单元测试的快感! 首先新建一个项目叫JUnit_Test,我们编写一个Calculator类,这是一个能够简单实现加减乘除 ...

  5. [转载]基于TFS实践敏捷-实现用户场景

    您是新用户的 Visual Studio 应用程序生命周期管理 (ALM) 和 Team Foundation Server (TFS) 吗? 您想知道如何您和您的团队可以获得最大受益的这些工具来生成 ...

  6. 单元测试与Nunit的基本使用

    一.单元测试是什么 单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证.对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如C语言中单元指一个函数,C# ...

  7. 解决JS浮点数(小数)计算加减乘除的BUG

    在JavaScript中输出下面这些数值(注意不能作为字符串输出):0.1000000000000000000000000001(28位小数).0.10000000000000000000000000 ...

  8. Deep Learning 8_深度学习UFLDL教程:Stacked Autocoders and Implement deep networks for digit classification_Exercise(斯坦福大学深度学习教程)

    前言 1.理论知识:UFLDL教程.Deep learning:十六(deep networks) 2.实验环境:win7, matlab2015b,16G内存,2T硬盘 3.实验内容:Exercis ...

  9. junit基础篇、中级篇-实例代码

    学习文章: http://blog.csdn.net/andycpp/article/details/1327147 http://wenku.baidu.com/link?url=C27gDEj0l ...

随机推荐

  1. VBA 禁止保存

    禁止保存 在workbook事件中 Private Sub Workbook_BeforeClose(Cancel As Boolean)    Me.Saved = TrueEnd Sub Priv ...

  2. 2018.8.14-C#复习笔记总

    using System; using System.Collections.Generic; //using System.Linq; using System.Text; using System ...

  3. 趣味编程:CPS风格代码(Java 8,Functional Java版)

    CPS风格代码(Java 8版) package fp; import java.util.function.IntConsumer; public class CPS { static int ad ...

  4. Session的常用场景

    session :存储浏览器sessionID值保存在客户端,sessionID的key:data 数据存储在服务器上 会话管理,用户登录验证,权限访问控制,购物车,临时数据.

  5. html5中的SessionStorage 和localStorage

    html5中的Web Storage包括了两种存储方式:sessionStorage和localStorage. sessionStorage用于本地存储一个会话(session)中的数据,这些数据只 ...

  6. a标签伪类的LOVE HATE原则

    a标签伪类的LOVE HATE原则 a标签有四个伪类,分别是: a:link 未访问的链接 a:visited 已访问的链接 a:hover 鼠标移动到链接上 a:active 选定的链接 遇到的问题 ...

  7. visual code golang配置

    前言 其实环境搭建没什么难的,但是遇到一些问题,主要是有些网站资源访问不了(如:golang.org), 导致一些包无法安装,最终会导致环境搭建失败,跟据这个教程几步,我们将可以快速的构建golang ...

  8. python scikit-learn 安装中的各种事宜

    由于兴趣,想安装scikit,但是安装时提示pip版本低,让更新,但是他给的更新命令用了之后并不能更新成功(我是指我的) 网上的各种命令都试过了,弄了大半天还是不行,后来我把SCIKIT换成(whl- ...

  9. python笔记之循环控制

    学习python的第一个例子,while循环中嵌套if-else语句,一个猜年龄的例子 #案例1,实现循环猜年龄 # my_age = 12 # while True: # guess_age1 = ...

  10. PHP资源列表(转)

    一个PHP资源列表,内容包括:库.框架.模板.安全.代码分析.日志.第三方库.配置工具.Web 工具.书籍.电子书.经典博文等等. 初始翻译信息来自:<推荐!国外程序员整理的 PHP 资源大全& ...