Find the squareroot

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!

时间: 2024-11-03 21:42:30

Find the squareroot的相关文章

Radio Basics for RFID

Radio Basics for RFID (2015/09/24 22:30:37) Radio Basics for RFID (2015/09/24 22:30:37) Radio Basics for RFID (2015/09/24 22:30:37) Radio Basics for RFID (2015/09/24 22:30:37) Radio Basics for RFID (2015/09/24 22:30:37) Radio Basics for RFID (2015/09

Junit(1)在Eclipse中使用JUnit4进行单元测试

我们在编写大型程序的时候,需要写成千上万个方法或函数,这些函数的功能可能很强大,但我们在程序中只用到该函数的一小部分功能,并且经过调试可以确定,这 一小部分功能是正确的.但是,我们同时应该确保每一个函数都完全正确,因为如果我们今后如果对程序进行扩展,用到了某个函数的其他功能,而这个功能有bug的话,那绝对是一件非常郁闷的事情.所以说,每编写完一个函数之后,都应该对这个函数的方方面面进行测试,这样的测试我们称之为单元测试. 传统的编程方式,进行单元测试是一件很麻烦的事情,你要重新写另外一个程序,在

Junit(2)小试牛刀

我们继续对初级篇中的例子进行分析.初级篇中我们使用Eclipse自动生成了一个测试框架,在这篇文章中,我们来仔细分析一下这个测试框架中的每一个细节,知其然更要知其所以然,才能更加熟练地应用JUnit4. 一.包含必要地Package 在测试类中用到了JUnit4框架,自然要把相应地Package包含进来.最主要地一个Package就是org.junit.*.把它包含进来之后,绝大部分功能就有了.还有一句话也非常地重要"import static org.junit.Assert.*;"

JUNIT

jUnit4概述 jUnit4是JUnit框架有史以来的最大改进,其主要目标便是利用Java5的Annotation特性简化测试用例的编写. 先简单解释一下什么是Annotation,这个单词一般是翻译成元数据.元数据是什么?元数据就是描述数据的数据.也就是说,这个东西在Java里面可以用来和public.static等关键字一样来修饰类名.方法名.变量名.修饰的作用描述这个数据是做什么用的,差不多和public描述这个数据是公有的一样.想具体了解可以看Core    Java2.废话不多说了,

JUnit 4 使用教程

JUnit4是JUnit框架有史以来的最大改进,其主要目标便是利用Java5的Annotation特性简化测试用例的编写. 我们先看一下在JUnit 3中我们是怎样写一个单元测试的.比如下面一个类: package junit; public class AddOperation { public int add(int x,int y){ return x+y; } } 我们要测试add这个方法,我们写单元测试得这么写: package junit; import junit.framewor

屏幕 Dynpro

声明:原创作品,转载时请注明文章来自SAP师太技术博客:www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将追究法律责任!原文链接:http://www.cnblogs.com/jiangzhengjun/p/4292250.html 对话屏幕Dynpro(SE51). 11 屏幕元素... 11 屏幕属性... 11 PAI事件的触发.屏幕元素Function Code设置... 12 屏幕流逻辑Screen Flow Logic. 12 对话屏幕

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

转载自:http://blog.csdn.net/andycpp/article/details/1327147/ 我们在编写大型程序的时候,需要写成千上万个方法或函数,这些函数的功能可能很强大,但我们在程序中只用到该函数的一小部分功能,并且经过调试可以确定,这一小部分功能是正确的.但是,我们同时应该确保每一个函数都完全正确,因为如果我们今后如果对程序进行扩展,用到了某个函数的其他功能,而这个功能有bug的话,那绝对是一件非常郁闷的事情.所以说,每编写完一个函数之后,都应该对这个函数的方方面面进

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

通过前 2 篇文章,您一定对 JUnit 有了一个基本的了解,下面我们来探讨一下 JUnit4 中一些高级特性. 一.     高级 Fixture 上一篇文章中我们介绍了两个 Fixture 标注,分别是 @Before 和 @After ,我们来看看他们是否适合完成如下功能:有一个类是负责对大文件(超过 500 兆)进行读写,他的每一个方法都是对文件进行操作.换句话说,在调用每一个方法之前,我们都要打开一个大文件并读入文件内容,这绝对是一个非常耗费时间的操作.如果我们使用 @Before 和

(转载)3D 图形编程的数学基础(1) 向量及其运算

原文地址:http://blog.csdn.net/vagrxie/article/details/4960473 版权声明:本作品由九天雁翎创作,采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可.http://www.jtianling.com 目录(?)[+] write by 九天雁翎(JTianLing) -- blog.csdn.NET/vagrxie 讨论新闻组及文件 Technorati 标签: 向量,3D,坐标系,规范化,点积,叉积 说明 因为大学时在高等数学课程中学