Created
April 25, 2018 00:54
-
-
Save ffuentese/71c75d85646c370f04eca324badedd9c to your computer and use it in GitHub Desktop.
Sieve of erathostenes to file in C / Criba de eratóstenes en C a archivo de texto
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 <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#include <stdbool.h> | |
int main() | |
{ | |
FILE * fp; | |
char output[] = "result.txt"; // filename | |
char s[15]; | |
fp = fopen(output, "w+"); | |
int num = 0; | |
printf("CALCULADORA DE PRIMOS\n"); | |
printf("Ingrese un valor limite\n"); // Enter the limit value | |
fgets(s, 15, stdin); | |
num = strtol(s, NULL, 10); | |
bool *flags; | |
flags = malloc(sizeof(int)*num); // allocates space for array | |
for(int i = 0; i < num; i++) | |
{ | |
flags[i] = true; // fills up array with "true" values | |
} | |
int upperLimit = sqrt(num); // gets the square number | |
for(int i = 2; i <= upperLimit; i++) | |
{ | |
if(flags[i]) | |
{ | |
for(int j = i * i; j < num; j += i) | |
{ | |
flags[j] = false; // discards multiples from array | |
} | |
} | |
} | |
for(int i = 2; i < num; i++) | |
{ | |
if(flags[i]) // if number is marked as true | |
{ | |
fprintf(fp,"%d,", i); // copy "survivors" into txt file | |
} | |
} | |
fclose(fp); // closes file | |
printf("Los primos hasta el %d en: %s \n", num, output); // Primes up to the limit number go to file | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment