We are tasked with finding the n
-th element of an infinite sequence defined as follows:
0, 1, 1, 2, 3, 5, 8, 13, 12, 7, 10, 8, 9, ...
- The
0th
element of the sequence is0
. - The
1st
element of the sequence is1
. - Each successive element is calculated as the sum of the separate digits of the two previous elements.
- Given
n = 2
, the function should return1
. - Given
n = 6
, the function should return8
. - Given
n = 10
, the function should return10
.
n
is an integer within the range0..1,000,000,000
.- You should write an efficient algorithm that handles large values of
n
effectively.
-
Write a function with the following signature:
function digits_sequence(int $n): int;
-
Optimize the function for:
- Time complexity: Handle up to ( n = 1,000,000,000 ).
- Memory complexity: Use minimal memory for storing intermediate values.
-
(Optional but recommended) Dockerize the solution for easy testing and deployment.
-
Write unit tests to validate the correctness of the function.
<?php
echo digits_sequence(10); // Output: 10
- Use cycle detection to improve efficiency when repetitive patterns are observed in the sequence.
- Handle edge cases such as
n = 0
andn = 1
separately. - Include helper functions if necessary to keep the main function clean and readable.
digits_sequence.php
: Implementation of the function.tests/
: Unit tests for verifying the correctness of the function.Dockerfile
: Docker setup for running the solution.README.md
: Explanation of the problem and how to run the solution.
Run some digit example
make run_example
Run the tests
make run_tests