Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> // cout
- #include <math.h> // sqrt
- #include <time.h> // clock/CLOCKS_PER_SEC
- #include <stdlib.h> // malloc/free
- using namespace std;
- int main(int argc, const char * argv[]) {
- int n = 1000000000;
- int i;
- int j;
- int k;
- int s;
- int c;
- int sr;
- int * a = (int*)malloc((size_t)n * sizeof(int));
- for(i = 0; i < n; i++) {
- a[i] = 1;
- }
- clock_t t = clock();
- sr = sqrt(n);
- for(i = 2; i <= sr; i++) {
- if(a[i]) {
- s = i * i;
- for(k = 0, j = 0; j <= n; j = s + (k * i), k++) {
- a[j] = 0;
- }
- }
- }
- t = clock() - t;
- c = 0;
- for(i = 2; i < n; i++) {
- if(a[i]) {
- //cout << i << " ";
- c++;
- }
- }
- cout << fixed << "\nCalculated " << c << " prime numbers up to " << n << " in " << t << " clocks (" << ((float)t) / CLOCKS_PER_SEC << " seconds).\n";
- free(a);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement