DEV Community

Cover image for CODING JOURNEY DAY 2
Sabarish  M S
Sabarish M S

Posted on

CODING JOURNEY DAY 2

๐Ÿš€ 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)