![]() |
VOOZH | about |
Given an integer n. Print first n elements of Recaman’s sequence. Recaman's Sequence starts with 0 as the first term. For each next term, calculate previous term - index (if positive and not already in sequence); otherwise, use previous term + index.
Examples:
Input: n = 6
Output: 0, 1, 3, 6, 2, 7
Explanation: According to Recaman's Sequence:
- 0 (first term)
- 0 - 1 is negative, so use 0 + 1 = 1
- 1 - 2 is negative, so use 1 + 2 = 3
- 3 - 3 is 0, already in sequence, so use 3 + 3 = 6
- 6 - 4 = 2 (not in sequence, so use it)
- 2 - 5 is negative, so use 2 + 5 = 7
Input: n = 17
Output: 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8
Table of Content
The idea is to generate the first n terms of Recaman’s sequence by following its recurrence rule. We start with 0 and iteratively compute the next term as previous term - index if it is positive and not already in sequence; otherwise, we use previous term + index.
0 1 3 6 2 7
The idea is to construct Recaman's sequence efficiently by using hashing to track visited numbers. The approach iterates from 1 to n, computing a candidate value as the previous term minus the index. If this candidate is negative or already exists in seen, we instead add the index. This ensures each number is unique while following the sequence rules.
0 1 3 6 2 7