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 find last digit of the given sequence for given n in Python
We need to find the last digit of a sequence S for a given value n. The sequence S is defined by a mathematical formula involving powers of 2.
Understanding the Problem
The sequence formula is complex, but we can simplify it to find only the last digit. For n = 2, we calculate specific terms and sum them to get 126, where the last digit is 6.
Algorithm Steps
To solve this problem efficiently ?
- Initialize total = 0 and temp = 1
- While temp ? n, add (2^temp mod 10) to total
- Multiply temp by 2 for next iteration
- Apply final multiplication factor based on whether n is odd or even
- Return the last digit
Example
Here's the implementation to find the last digit of the sequence ?
def solve(n):
total = 0
temp = 1
while temp <= n:
total += pow(2, temp, 10) # 2^temp mod 10
temp *= 2
total = total * (1 + (4 if n % 2 == 1 else 0)) % 10
return total
# Test with n = 2
n = 2
result = solve(n)
print(f"For n = {n}, last digit is: {result}")
# Test with additional values
test_cases = [1, 3, 4, 5]
for n in test_cases:
print(f"For n = {n}, last digit is: {solve(n)}")
For n = 2, last digit is: 6 For n = 1, last digit is: 2 For n = 3, last digit is: 2 For n = 4, last digit is: 6 For n = 5, last digit is: 6
How It Works
The algorithm uses modular arithmetic to find only the last digit instead of computing huge numbers. The pow(2, temp, 10) function efficiently calculates 2^temp mod 10. The final multiplication factor depends on whether n is odd (multiply by 5) or even (multiply by 1).
Key Points
- We use
pow(a, b, m)for efficient modular exponentiation - Only the last digit matters, so we work with mod 10 throughout
- The algorithm handles the complex mathematical sequence efficiently
Conclusion
This solution efficiently finds the last digit of a complex sequence using modular arithmetic. The key insight is avoiding large number calculations by working with remainders throughout the process.
