HackerRank python练习——Sherlock and Squares

    技术2024-10-14  53

    Sherlock and Squares

    题目链接

    写代码:

    def squares(a, b): counts = 0 for i in range(a,b+1): s = int(math.sqrt(i)) if pow(s,2) == i: counts += 1 return counts

    思路是遍历a到b,将每个元素i开平方根并取整,如果取整后的数字平方后与i相等,则是完全平方数,counts加1. 结果:

    报错:Your code did not execute within the time limits.

    改后代码:

    def squares(a, b): counts = 0 end = round(math.sqrt(b)) for i in range(1,end+1): s = i ** 2 if s in range(a,b+1): counts += 1 return counts

    思路是从1开始遍历,若这个数的平方在a和b之间,则counts加1. 也可以从a开平方根后四舍五入后的数开始遍历,只要这个数的平方在a到b之间,counts则加1:

    def squares(a, b): counts = 0 start = round(a ** 0.5) end = round(b ** 0.5) for i in range(start,end + 1): if i ** 2 in range(a,b+1): counts += 1 return counts

    用while循环语句写:

    def squares(a, b): counts = 0 c = 1 d = c ** 2 while d <= b: if d >= a: counts += 1 c += 1 d = c ** 2 return counts
    Processed: 0.013, SQL: 9