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
-
Economics & Finance
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 places to reach at position 3, then jump three positions to reach at 6 and so on. We have to check whether maintaining this pattern, 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
Approach
To solve this, we will follow these steps −
- Calculate j := (1 + square root of (1+8*n)) / 2
- If |j - int part of j| <= 0, then
- return True
- Otherwise return False
How It Works
This problem is essentially checking if n can be expressed as a triangular number. The formula for the k-th triangular number is k*(k+1)/2. We solve the quadratic equation k*(k+1)/2 = n to find if there exists an integer k.
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))
The output of the above code is −
True
Alternative Implementation
Here's a cleaner version that checks if j is exactly an integer −
from math import sqrt
def can_reach_position(n):
# Using quadratic formula to solve k*(k+1)/2 = n
j = (-1 + sqrt(1 + 8 * n)) / 2
return j == int(j)
# Test with different values
test_values = [1, 3, 6, 10, 15, 21, 28]
for n in test_values:
result = can_reach_position(n)
print(f"n = {n}: {result}")
The output of the above code is −
n = 1: True n = 3: True n = 6: True n = 10: True n = 15: True n = 21: True n = 28: True
Conclusion
This algorithm efficiently determines if a position n can be reached by sequential jumps using the mathematical property of triangular numbers. The solution runs in O(1) time complexity.
