题目链接
思路是遍历a到b,将每个元素i开平方根并取整,如果取整后的数字平方后与i相等,则是完全平方数,counts加1. 结果:
报错:Your code did not execute within the time limits.
思路是从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