Created
August 4, 2014 07:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
動作: http://melpon.org/wandbox/permlink/8gp2KOUYiQPRSq7r
Sample Input
10
3
11
Output for the Sample Input
4
2
5