For modulus 10 the Pisano period P is 60, so F(n+2) mod 10 = F((n+2) % 60) mod 10. Reducing the index to k = (n+2) % 60 makes the value easy to compute by simple iteration.
classSolution {
public:int sum_last_digit_str(const std::string &s) {
// reduce n modulo 60
int k =0;
for (char ch : s) { k = (k*10+ (ch -'0')) %60; }
k = (k +2) %60; // n+2
int a =0, b =1;
for (int i =0; i < k; ++i) { int nxt = (a + b) %10; a = b; b = nxt; }
int res = (a -1+10) %10;
return res;
}
};
1
2
3
4
5
6
7
8
9
10
packagemainfuncSumLastDigitStr(sstring) int {
k:=0for_, ch:=ranges { k = (k*10+ int(ch-'0')) %60 }
k = (k+2) %60a, b:=0, 1fori:=0; i < k; i++ { a, b = b, (a+b)%10 }
return (a-1+10)%10}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintsumLastDigitStr(String s) {
int k = 0;
for (char ch : s.toCharArray()) { k = (k*10 + (ch -'0')) % 60; }
k = (k + 2) % 60;
int a = 0, b = 1;
for (int i = 0; i < k; ++i) { int nxt = (a + b) % 10; a = b; b = nxt; }
return (a - 1 + 10) % 10;
}
}
1
2
3
4
5
6
7
8
9
10
objectSolution {
funsumLastDigitStr(s: String): Int {
var k = 0for (ch in s) k = (k*10 + (ch - '0')) % 60 k = (k + 2) % 60var a = 0; var b = 1 repeat(k) { val nxt = (a + b) % 10; a = b; b = nxt }
return (a - 1 + 10) % 10 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsum_last_digit_str(self, s: str) -> int:
k =0for ch in s:
k = (k*10+ (ord(ch) -48)) %60 k = (k +2) %60 a, b =0, 1for _ in range(k):
a, b = b, (a + b) %10return (a -1+10) %10defsum_last_digit(self, n: int) -> int:
return self.sum_last_digit_str(str(n))
1
2
3
4
5
6
7
8
9
10
11
pubstructSolution;
impl Solution {
pubfnsum_last_digit_str(s: &str) -> u8 {
letmut k: usize=0;
for ch in s.bytes() { k = (k*10+ (ch -b'0') asusize) %60; }
k = (k +2) %60;
let (mut a, mut b) = (0u8, 1u8);
for _ in0..k { let nxt = (a + b) %10; a = b; b = nxt; }
((a +9) %10)
}
}
⏰ Time complexity: O(L + P) where L is length of decimal n (to reduce mod 60) and P=60 for the iteration; overall O(L + 60) -> O(L) for large-string n.
After reducing the index to k = (n+2) % 60, computing F(k) can be done with fast-doubling in O(log k); since k ≤ 60 this is tiny, but fast-doubling is useful if modulus or period were larger.
deffib_pair(n: int, mod: int):
if n ==0: return (0,1)
a,b = fib_pair(n>>1, mod)
c = (a * ((2*b - a) % mod)) % mod
d = ((a*a) % mod + (b*b) % mod) % mod
if n &1:
return (d, (c+d) % mod)
else:
return (c, d)
defsum_last_digit_fast(n_str: str) -> int:
# reduce and compute k =0for ch in n_str: k = (k*10+ (ord(ch)-48)) %60 k = (k+2) %60return (fib_pair(k, 10)[0] -1+10) %10