Skip to content

Instantly share code, notes, and snippets.

@ateruimashin
Last active December 22, 2021 08:36
Show Gist options
  • Save ateruimashin/6a1a6352d25b77f5aa2b64dfba0c533c to your computer and use it in GitHub Desktop.
Save ateruimashin/6a1a6352d25b77f5aa2b64dfba0c533c to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep2(i, s, n) for (int i = (s); i < (n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;
//その他の素数リストの取得の仕方は以下のリンクに4例示しています。
// https://gist.github.com/ateruimashin/68e23d570ca15dc8ecf6c8366fbdf987
//素朴な素数判定から無駄を省いた判定方法
//素数判定はたかだかsqrt(N)まででよい。
vector<int> solve2(int n) {
int num = 2;
vector<int> ans;
while (num <= n) {
// 2は素数なので答えに入れる
if (num == 2) {
ans.push_back(num);
} else if (num % 2 == 0) {
// 2の倍数は2以外弾く
num++;
continue;
} else {
//奇数のみ素数判定する。たかだかsqrt(N)まで調べれば良い。
// jが偶数の時は判定する意味がないので、jは常に奇数にする。
bool flag = 1;
for (int j = 3; j * j <= num; j += 2) {
if (num % j == 0) {
flag = 0;
break;
}
}
if (flag) ans.push_back(num);
}
num++;
}
return ans;
}
// vector内の要素の表示をする関数
void printAns(vector<int> ans) {
for (int num : ans) cout << num << " ";
cout << endl;
}
int main() {
//求める最大値を設定
int numMax = 100;
//素数列を求める(このアルゴリズムで解くと必ず昇順になる)
auto ans2 = solve2(numMax);
//素数列の表示
printAns(ans2);
//求める番目を初期化(-1はエラー)
int whereNum = -1;
//求める番目を入力させる。(1~素数列の最大サイズまで)
while (whereNum > ans2.size() || whereNum <= 0) {
cout << ans2.size() << "以下の数値を入力" << endl;
cin >> whereNum;
}
// vectorのindexに合わせるためにデクリメント
//[BugFixed]デクリメントするタイミング間違えててバグらせていました
whereNum--;
//結果を出力する
cout << ans2[whereNum] << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment