Skip to content

Instantly share code, notes, and snippets.

@chomado
Created August 4, 2014 07:56
Show Gist options
  • Save chomado/649dd929894070117cce to your computer and use it in GitHub Desktop.
Save chomado/649dd929894070117cce to your computer and use it in GitHub Desktop.
n(入力int)以下の素数がいくつあるかを出力する。 http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0009&lang=jp
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
//素数かどうかが真のものの数(カウントアップ)を返す
int countup(vector<bool>::iterator begin, vector<bool>::iterator end)
{
int counter = 0;
while (begin++ != end) {
if (*begin)
counter++;
}
return counter;
}
int main()
{
int n;
while (cin >> n) {
int max = sqrt(static_cast<double>(n));
vector<bool> is_prime(n, true);
vector<bool>::iterator begin, end;
is_prime[0] = is_prime[1] = false;
for (int i=2; i<=max; i++) {
if (!is_prime[i]) {
continue;
}
else { // iがもし素数だったら、(自分以外の)その倍数全部潰す
for (int cntr = 2, j = 2*i; j<=n; j = i*(cntr++)) {
is_prime[j] = false;
}
}
}
begin = is_prime.begin();
end = is_prime.end();
cout << countup(begin, end) << endl;
}
}
@chomado
Copy link
Author

chomado commented Aug 4, 2014

動作: http://melpon.org/wandbox/permlink/8gp2KOUYiQPRSq7r
Sample Input
10
3
11

Output for the Sample Input
4
2
5

@minamiyama1994
Copy link

内のcountを使うと吉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment