gpt4 book ai didi

python - 当 Python 中的输入量很大时如何有效地找到一个范围内的完美平方

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:41 25 4
gpt4 key购买 nike

问题是当输入非常大时,如何在给定范围内有效地找到完美平方。我的解决方案是给出 Time Limit Exceeded 错误。我已经检查了以下链接,但它们没有解决我的问题:
- Python Program on Perfect Squares
- How could I check if a number is a perfect square?
- Fastest way to determine if an integer's square root is an integer (我不知道如何在 Python 中实现此链接中给出的解决方案)。

题目问题是:

Input Format: First line contains T, the number of testcases. T test cases follow, each in a newline. Each testcase contains two space separated integers denoting A and B. Find all the perfect squares in the range A and B (both inclusive).

输入示例:

23 917 24

The code I wrote is:

import math
def is_perfect_square(n):
return n % n**0.5 == 0

t = int(raw_input())
for i in range(t):
numbers = map(int, raw_input().split())
count = 0
for j in xrange(numbers[0], numbers[1] + 1): # I also tried range() which gave memory error
if (is_perfect_square(j)):
count = count + 1

print count

虽然此代码适用于较小的数字,但对于较大的输入会出现 Time limit exceeded 错误。

(注意:gmpy 不是一个选项,因为代码必须在没有 gmpy 模块的在线编译器上运行)

最佳答案

与其从 A 循环到 B 并检查完美平方,为什么不循环遍历从 sqrt(A)sqrt(B) 和平方,给出你的答案。

例如,让我们求出 1000 到 2000 之间的平方数:

sqrt(1000) = 31.6  -->  32  (need the ceiling here)
sqrt(2000) = 44.7 --> 44 (need the floor here)

因此,我们的答案是:

322 = 1024332 = 1089342 = 1156352 = 1225362 = 1296372 = 1369382 = 1444392 = 1521402 = 1600412 = 1681422 = 1764432 = 1849442 = 1936

关于python - 当 Python 中的输入量很大时如何有效地找到一个范围内的完美平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com