📜  Recaman 序列(1)

📅  最后修改于: 2023-12-03 15:04:52.004000             🧑  作者: Mango

Recaman Sequence

The Recaman sequence is a mathematical sequence defined as follows:

  1. The first term of the sequence is 0.
  2. For every subsequent term n (starting from 1), if n - term[n-1] is positive and not already present in the sequence, then the term is n - term[n-1]; otherwise, the term is n + term[n-1].

The sequence is named after the Colombian mathematician Bernardo Recaman Santos.

Implementation in Python

Here is a sample implementation of the Recaman sequence in Python:

def recaman_sequence(n):
    sequence = [0]
    lookup = set(sequence)
    for i in range(1, n):
        if sequence[i-1] - i > 0 and sequence[i-1] - i not in lookup:
            sequence.append(sequence[i-1] - i)
        else:
            sequence.append(sequence[i-1] + i)
        lookup.add(sequence[i])
    return sequence

The function recaman_sequence(n) takes an integer n as input and returns a list containing the first n terms of the Recaman sequence.

Example Usage
n = 10
sequence = recaman_sequence(n)
print(sequence)

Output:

[0, 1, 3, 6, 2, 7, 13, 20, 12, 21]
Visualization

To visualize the Recaman sequence, you can use various plotting libraries in Python like matplotlib. Here is an example of how you can plot the sequence:

import matplotlib.pyplot as plt

n = 100
sequence = recaman_sequence(n)

x = range(n)
y = sequence

plt.plot(x, y, marker='o')
plt.xlabel("Index")
plt.ylabel("Value")
plt.title("Recaman Sequence")
plt.grid(True)
plt.show()

This code will generate a plot showing the Recaman sequence up to the specified number of terms.

Conclusion

The Recaman sequence is an interesting mathematical sequence with unique properties. It has applications in number theory, recreational mathematics, and algorithmic art. Implementing and exploring the Recaman sequence can be a fun programming exercise.