#B4092. Divisibility Count in Concatenated Number Sequence
Divisibility Count in Concatenated Number Sequence
Divisibility Count in Concatenated Number Sequence
A mysterious creature challenges you with a mathematical puzzle. The creature has written a sequence of numbers on the ground which are formed by concatenating the natural numbers incrementally:
\(1,\; 12,\; 123,\; 1234,\; 12345,\; \dots,\; 12345678910,\; \dots,\; 1234567891011,\; \dots\)
The kth term in the sequence is the number formed by concatenating together the numbers 1, 2, 3, ..., k. The creature then challenges: "If you can compute how many of the first \(n\) terms of this sequence are divisible by \(3\), I will let you pass. Otherwise... well, I might have to eat you!"
Your task is to help solve this puzzle. Note that a number is divisible by \(3\) if and only if the sum of its digits is divisible by \(3\). For the kth term, the sum of its digits is equal to \(\sum_{i=1}^{k} s(i)\), where \(s(i)\) is the sum of the digits of \(i\). Since for any positive integer \(i\), we have \(s(i) \equiv i \pmod{3}\), the digit sum modulo \(3\) is equivalent to the sum \(1+2+\cdots+k = \frac{k(k+1)}{2}\).
Thus the problem reduces to counting the number of integers \(k\) (with \(1 \le k \le n\)) such that
\(\frac{k(k+1)}{2} \equiv 0 \pmod{3}\).
It can be proven that this congruence holds if and only if \(k \equiv 0\) or \(k \equiv 2 \pmod{3}\). Your program should compute the total count of such \(k\) values.
inputFormat
The input consists of a single integer \(n\) representing the number of terms to consider in the sequence.
outputFormat
Output a single integer indicating how many of the first \(n\) terms of the sequence are divisible by \(3\).
sample
6
4