Skip to content

Instantly share code, notes, and snippets.

@jordi-petit
Last active April 26, 2018 07:31
Show Gist options
  • Save jordi-petit/dc4c22dddd0a793a7c4fd83f7ae2401e to your computer and use it in GitHub Desktop.
Save jordi-petit/dc4c22dddd0a793a7c4fd83f7ae2401e to your computer and use it in GitHub Desktop.
AP1 2017-12-01 Garbell d'Eratòstenes
// Programa per trobar tots els primers entre 0 i n.
// Implementació amb n+1 crides a es_primer()
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
double now() {
return clock() / double(CLOCKS_PER_SEC);
}
bool es_primer(int x) {
if (x <= 1) return false;
for (int d = 2; d*d <= x; ++d) {
if (x%d == 0) {
return false;
}
}
return true;
}
int main() {
int n;
cin >> n;
double t1 = now();
vector<bool> p(n+1);
for (int i = 0; i <= n; ++i) {
p[i] = es_primer(i);
}
double t2 = now();
for (int i = 0; i <= n; ++i) if (p[i]) cout << i << endl;
cout << endl << t2 - t1 << endl;
}
// Programa per trobar tots els primers entre 0 i n.
// Implementació amb Garbell d'Erastòtones
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
double now() {
return clock() / double(CLOCKS_PER_SEC);
}
int main() {
int n;
cin >> n;
double t1 = now();
vector<bool> p(n+1, true);
p[0] = p[1] = false;
for (int i = 2; i*i <= n; ++i) {
if (p[i]) {
for (int j = i+i; j <= n; j += i) {
p[j] = false;
}
}
}
double t2 = now();
for (int i = 0; i <= n; ++i) if (p[i]) cout << i << endl;
cout << endl << t2 - t1 << endl;
}
@jordi-petit
Copy link
Author

jordi-petit commented Dec 1, 2017

A classe no he fet bé la mesura dels temps. 😪

Amb n = 10000000, el p1 em triga 4.032 segons, en canvi p2 triga 0.027 segons. Amb això comprovem que a la pràctica Eratòstenes és més eficient! 👍

Proveu-ho al vostre ordinador! 🖥️

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