Python程序检查能否通过跳跃到达位置n
假设有一条从1到n的数轴。一开始我们在位置0,跳一步到1,然后跳两格到3,再跳三格到6,以此类推。我们需要检查是否能按照这种方式到达位置n。
所以,如果输入n = 21,则输出为True,因为1+2+3+4+5+6 = 21
为了解决这个问题,我们将遵循以下步骤:
- j:= (1 + √(1+8*n)) / 2
- 如果|j - j的整数部分| <= 0,则
- 返回True
- 否则返回False
示例
让我们看看下面的实现以更好地理解:
from math import sqrt def solve(n): j=(1+sqrt(1+8*n))/2 if abs(j-int(j))<=0: return True else: return False n = 21 print(solve(n))
输入
21
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
True
广告