forked from Twiggecode/Integer-Sequences
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecaman_sequence.cpp
44 lines (32 loc) · 904 Bytes
/
recaman_sequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
C++ Program to find the nth number of Recaman Sequence
*/
#include <bits/stdc++.h>
using namespace std;
vector<int> findRecamanSequence(int n) {
vector<int> recamanSequence;
recamanSequence.push_back(0);
map<int, bool> isExist;
isExist[0] = true;
for (int i = 1; i <= n; i++) {
int prev = recamanSequence[i - 1];
if (prev - i > 0 && !isExist[prev - i]) {
recamanSequence.push_back(prev - i);
isExist[prev - i] = true;
} else {
recamanSequence.push_back(prev + i);
isExist[prev + i] = true;
}
}
return recamanSequence;
}
// Main Function
int main()
{
int n;
cout<< "Enter a number: ";
cin>> n;
vector<int> recamanSequence = findRecamanSequence(n);
cout<< "The " << n << "th number of recaman sequence is: " << recamanSequence[n] << "\n";
return 0;
}