commit 69aa4ce2ab42cf5bd5d5a7cb6380fe3314b32468
parent 3371fdfebda510381d276a60c5efc57916b6652f
Author: Martin Kloeckner <mjkloeckner@gmail.com>
Date: Tue, 26 Mar 2024 00:32:47 -0300
Abstract main code into it's own functions
In particular `void vector_discard_non_primes(std::vector<bool>& v)` and
`vector_export_to_file_path(numeros, fp, primes_found)`
`void vector_discard_non_primes(std::vector<bool>& v)` sets to false the
positions in the vector where the index is not a prime number,
`vector_export_to_file_path(numeros, fp, primes_found)` prints the index
of the vector where the index is a prime number, to an open file, the
primes_found reference is set to the number of printed primes
Diffstat:
1 file changed, 30 insertions(+), 17 deletions(-)
diff --git a/tps/1/main.cpp b/tps/1/main.cpp
@@ -11,22 +11,40 @@
#define OUTPUT_FILE_PATH "primos.txt"
const unsigned int MAXIMO = 100000000;
+void vector_discard_non_primes(std::vector<bool>& v) {
+ v[0] = v[1] = false; // 0 y 1 no son primos
+ for (size_t i = 2; i < std::sqrt(MAXIMO); ++i) {
+ if(v[i]) {
+ for (size_t j = i; j <= (MAXIMO/i); ++j) {
+ v[i*j] = false;
+ }
+ }
+ }
+}
+
+void vector_export_to_file_path(
+ const std::vector<bool> v,
+ std::ofstream& fp,
+ unsigned int &primes_written) {
+
+ primes_written = 0;
+ for (size_t i = 2; i < v.size(); ++i) {
+ if(v[i]) {
+ fp << i << std::endl;
+ primes_written++;
+ }
+ }
+}
+
int main (void) {
- unsigned long ti, i, j;
+ unsigned int ti, primes_found;
double tt;
std::ofstream fp;
std::vector<bool> numeros(MAXIMO, true);
ti = clock();
- numeros[0] = numeros[1] = false; // 0 y 1 no son primos
- for (i = 2; i < std::sqrt(MAXIMO); ++i) {
- if(numeros[i]) {
- for (j = i; j <= (MAXIMO/i); ++j) {
- numeros[i*j] = false;
- }
- }
- }
+ vector_discard_non_primes(numeros);
fp.open(OUTPUT_FILE_PATH);
if (!fp.is_open()) {
@@ -34,14 +52,9 @@ int main (void) {
return -1;
}
- for (i = 2, j = 0; i < numeros.size(); ++i) {
- if(numeros[i]) {
- fp << i << std::endl;
- j++;
- }
- }
-
+ vector_export_to_file_path(numeros, fp, primes_found);
fp.close();
+
tt = (double(clock() - ti)) / CLOCKS_PER_SEC;
std::cout.precision(2);
@@ -53,7 +66,7 @@ int main (void) {
}
std::cout << std::fixed
- << "Se encontraron `" << j
+ << "Se encontraron `" << primes_found
<< "` numeros primos en `"
<< tt << "` " << t_unit << std::endl;