课后作业求阶梯数的问题
steps = 7i = 1
FIND = False
while i < 100:
if (steps % 7 == 0) and (steps % 6 == 5) and (steps % 5 == 4) and(steps % 3 == 2) and (steps % 2 == 1) :
FIND = True
break
i = i + 1
if FIND == True:
print('阶梯数是:', steps)
else:
print('在程序限定的范围内找不到答案!')
为什么把steps能被7整除写成(steps % 7 == 0) 并且写到 if 里面不行,要写成下面这样才行?
为什么把steps能被7整除写成(steps % 7 == 0) 并且写到 if 里面不行,要写成下面这样才行?
steps = 7
i = 1
FIND = False
while i < 100:
if (steps % 2 == 1) and (steps % 3 == 2) and (steps % 5 == 4) and (steps % 6 == 5):
FIND = True
break
else:
steps = 7 * (i + 1)
i = i + 1
if FIND == True:
print('阶梯数是:', steps)
else:
print('在程序限定的范围内找不到答案!') 本帖最后由 chinajz 于 2023-3-8 19:26 编辑
修改一下,也是可以的:
steps = 7
i = 1
FIND = False
while i < 100:
steps = i*7
if (steps % 7 == 0) and (steps % 6 == 5) and (steps % 5 == 4) and(steps % 3 == 2) and (steps % 2 == 1) :
FIND = True
break
i = i + 1
if FIND == True:
print('阶梯数是:', steps)
else:
print('在程序限定的范围内找不到答案!')
或者:
#steps = 7
i = 1
FIND = False
while i < 120:
if (i % 7 == 0) and (i % 6 == 5) and (i % 5 == 4) and(i % 3 == 2) and (i % 2 == 1) :
FIND = True
break
i = i + 1
if FIND == True:
print('阶梯数是:',i)
else:
print('在程序限定的范围内找不到答案!') 本帖最后由 chinajz 于 2023-3-8 19:20 编辑
理解完全是对的,只是7的倍数效率似乎更好些。
#steps = 7
i = 7
FIND = False
while i < 120:
if (i % 7 == 0) and (i % 6 == 5) and (i % 5 == 4) and(i % 3 == 2) and (i % 2 == 1) :
FIND = True
break
i = i + 7
if FIND == True:
print('阶梯数是:',i)
else:
print('在程序限定的范围内找不到答案!') def stepNumbers(a,b):
stepNumbers = []
if a > b:
a, b = b, a
k = a//7
for i in range(k*7, b, 7):
if i%2 == 1 and i%3 == 2 and i%4 == 3 and i%5 == 4 and i%6 == 5:
stepNumbers.append(i)
if stepNumbers == []:
print(f'[{a},{b}]之间没有阶梯数。')
else:
print(f'[{a},{b}]之间的阶梯数有{stepNumbers}')
页:
[1]