Problem
Given a number n, return the sum of the last digits of the first n odd numbers.
The last digits of the odd numbers cycle in a fixed pattern: 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, .... For n = 7 the odd numbers are 1, 3, 5, 7, 9, 11, 13, their last digits are 1, 3, 5, 7, 9, 1, 3, and the answer is 29.
Solution
There is no need to generate the odd numbers at all. The last digits repeat in a cycle of 5 (1 + 3 + 5 + 7 + 9 = 25), so:
- Every complete cycle of 5 odd numbers contributes exactly
25. Math.floor(n / 5)full cycles contributeq * 25.- The remaining
n % 5numbers take the firstrvalues of the cycle.
const sumLastDigitsOdd = (n: number): number => {
const cycle = [1, 3, 5, 7, 9];
const q = Math.floor(n / 5);
const r = n % 5;
let result = q * 25;
for (let i = 0; i < r; i++) {
result += cycle[i];
}
return result;
};
Complexity Analysis
| Measure | Complexity |
|---|---|
| Time Complexity | O(1) |
| Space Complexity | O(1) |
- The remainder loop runs at most 4 times regardless of
n
Notes
- Spotting the cycle turns an O(n) iteration into pure arithmetic. Works for any
n, including huge values where iterating would be slow. - The same divide-into-cycles idea applies to many digit and modulo problems.