
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to check robot can reach target position or not in Python
- Program to check whether we can reach last position from index 0 in Python
- Program to check we can update a list index by its current sum to reach target or not in python
- Program to check we can cross river by stones or not in Python
- Program to check whether we can get N queens solution or not in Python
- Program to check we can reach end of list by starting from k in Python
- Program to check person can reach top-left or bottomright cell avoiding fire or not in Python
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check we can form array from pieces or not in Python
- Python program to check whether we can pile up cubes or not
- Program to check we can spell out the target by a list of words or not in Python
- C++ code to check grasshopper can reach target or not
- Program to check we can visit any city from any city or not in Python

Advertisements