forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlucky_numbers.cpp
54 lines (47 loc) · 1.11 KB
/
lucky_numbers.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
45
46
47
48
49
50
51
52
53
54
//
// Lucky Numbers Implementation in C++
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/math
// https://github.com/allalgorithms/cpp
//
// Contributed by: Sathwik Matsa
// Github: @sathwikmatsa
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// returns a vector of int containing lucky numbers in range [1,n]
vector <int> lucky_numbers(int n){
vector <int> seive;
// store numbers from 1 to n in the vector
for(int i = 1; i<=n; i++){
seive.push_back(i);
}
int survivor = 1;
int delete_every = 2;
int index;
while(seive.size() >= delete_every){
index = delete_every-1;
while(index < seive.size()){
seive.erase(seive.begin()+index);
index+=(delete_every-1);
}
delete_every = survivor = (*(++find(seive.begin(), seive.end(), survivor)));
}
return seive;
}
int main(){
int n;
cout << "Enter a number: ";
cin>>n;
vector <int> luckyNumbers = lucky_numbers(n);
cout << "lucky numbers up to " << n << ":" <<endl;
for ( vector<int>::iterator it = luckyNumbers.begin() ; it < luckyNumbers.end(); it++ ){
cout << *it << " ";
}
cout<<endl;
return 0;
}