# 输出一定范围内的完全数 from math import sqrt def perfect(x, y): A = [] for a in range(x, y + 1): s = 1 for b in range(2, int(sqrt(a) + 1)): if a % b == 0: c = int(a / b) if b > c: break if b == c: s += b else: s += b + c if s == a: A += [a] if 1 in A: A.remove(1) print(A, end=f",共有{len(A)}个完全数\n") def isint(n): f = False if str(n).count(".") == 0 and str(n).count("-") == 0: f = True return f import time as t print("输入两个正整数") i = "0" while i == "0": try: x = int(input(':')) y = int(input(':')) except: print("重新输入!") else: if isint(x) and isint(y): t1 = t.time() perfect(x, y) t2 = t.time() print(f'用时:{round(t2 - t1, 2)}s') else: print("重新输入!") i = input("输入0以重新运行:")给这段代码加个实时变化的计时器
时间: 2024-02-14 10:12:20 浏览: 53
可以在 `perfect` 函数内部添加一个计时器,用于记录计算完全数的时间。具体实现可以在函数开始前记录当前时间,函数执行完毕后再记录一次时间,两次时间的差值即为计算时间。代码如下:
```python
from math import sqrt
import time
def perfect(x, y):
A = []
# 记录开始时间
start_time = time.time()
for a in range(x, y + 1):
s = 1
for b in range(2, int(sqrt(a) + 1)):
if a % b == 0:
c = int(a / b)
if b > c:
break
if b == c:
s += b
else:
s += b + c
if s == a:
A += [a]
if 1 in A:
A.remove(1)
print(A, end=f",共有{len(A)}个完全数\n")
# 记录结束时间
end_time = time.time()
# 计算时间差
elapsed_time = end_time - start_time
print(f'用时:{round(elapsed_time, 2)}s')
def isint(n):
f = False
if str(n).count(".") == 0 and str(n).count("-") == 0:
f = True
return f
print("输入两个正整数")
i = "0"
while i == "0":
try:
x = int(input(':'))
y = int(input(':'))
except:
print("重新输入!")
else:
if isint(x) and isint(y):
perfect(x, y)
else:
print("重新输入!")
i = input("输入0以重新运行:")
```
在 `perfect` 函数中,我们在计算完全数前记录当前时间,计算完毕后再记录一次时间,并计算时间差,最后输出结果。
阅读全文