Skip to content

Instantly share code, notes, and snippets.

@ffuentese
Created April 25, 2018 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ffuentese/71c75d85646c370f04eca324badedd9c to your computer and use it in GitHub Desktop.
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
#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