๐ Day 2 of My Coding Journey | GeeksforGeeks
Hello developers ๐
This is Sabarish M S from Government College of Engineering, Salem, Tamil Nadu, India ๐ฎ๐ณ.
Continuing my coding journey with GeeksforGeeks, hereโs my Day 2 progress.
๐น Problem Statement
You are given two very large integers in the form of strings:
a โ base
b โ exponent
Your task is to find the last digit of aแต.
๐น Examples
Input:
a = "3", b = "10"
Output:
9
Explanation:
3ยนโฐ = 59049 โ last digit is 9
Input:
a = "6", b = "2"
Output:
6
Explanation:
6ยฒ = 36 โ last digit is 6
๐น Constraints
1 โค |a|, |b| โค 1000
a and b are very large, so they cannot be converted to integers
๐น Key Insight (Mathematical Optimization)
The last digit of powers repeats in cycles of 4.
For example:
2 โ 2, 4, 8, 6 (cycle length = 4)
3 โ 3, 9, 7, 1
7 โ 7, 9, 3, 1
So instead of calculating aแต, we only need:
๐ last digit of a
๐ b % 4
๐น** Solution Approach**
Handle base cases:
If b = "0" โ result is 1
If a = "0" โ result is 0
Extract the last digit of a
Compute b % 4 manually (since b is a string)
If b % 4 == 0, treat it as 4
Compute power manually (no Math.pow)
Return result % 10
๐น Why This Approach?
โ
Handles very large numbers
โ
Avoids overflow
โ
No floating-point operations
โ
Interview-friendly logic
โ
Time Complexity: O(|b|)
โ
Space Complexity: O(1)
๐น What I Learned Today
How to work with huge numbers using strings
Importance of pattern recognition in math problems
Why optimization matters more than brute force
How interviewers expect logic over libraries
Top comments (0)