Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Program to check we can reach at position n by jumping or not in Python
Suppose there is a number line from 1 to n. At first we are at position 0, jump one step to go 1, then jump two place to reach at position 3, then jump three position to reach at 6 and so on. We have to check whether maintaining this, we can reach at position n or not.
So, if the input is like n = 21, then the output will be True, because 1+2+3+4+5+6 = 21
To solve this, we will follow these steps −
- j:= (1 + square root of (1+8*n)) / 2
- if |j - int part of j| <= 0, then
- return True
- otherwise return False
Example
Let us see the following implementation to get better understanding −
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))
Input
21
Output
True
Advertisements
