From eaa238a90067e9f9c43ab19e20e7f460cfe0588d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Ortega=20Froysa?= Date: Thu, 18 Oct 2018 14:56:15 +0200 Subject: [PATCH] Basic prime calculator. --- src/global.h | 38 +++++++++++++++++++++++++++++++++++++ src/main.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/global.h b/src/global.h index f810f65..95922b7 100644 --- a/src/global.h +++ b/src/global.h @@ -21,3 +21,41 @@ #ifndef VERSION # define VERSION "version" #endif + +/* argp variables */ +const char *argp_program_version = VERSION; +const char *argp_program_bug_address = ""; + +/* argp options */ +static char desc[] = "A parallelized prime number generator."; +/*static char args_doc[] = "--count= [--verbose]";*/ +static struct argp_option opts[] = { + { "count", 'c', "number", 0, "The number of primes to generate (default is 1000)", 0}, + { "verbose", 'v', 0, 0, "Print out discovered primes", 0 }, + { 0 } +}; + +struct args { + size_t count; + int verbose; +}; + +static error_t parse_opt(int key, char *arg, struct argp_state *state) { + struct args *args = state->input; + switch(key) + { + case 'c': + args->count = (size_t)atol(arg); + break; + case 'v': + args->verbose = 1; + break; + case ARGP_KEY_ARG: + return 0; + default: + return ARGP_ERR_UNKNOWN; + } + return 0; +} + +static struct argp argp = { opts, parse_opt, 0, desc, 0, 0, 0 }; diff --git a/src/main.c b/src/main.c index cac8b94..39744d8 100644 --- a/src/main.c +++ b/src/main.c @@ -17,11 +17,60 @@ */ #include +#include +#include +#include #include "global.h" +#include "linked_list.h" -int main() { - printf("Indivisible %s\n", VERSION); +int main(int argc, char *argv[]) { + struct args args = { 1000, 0 }; + argp_parse(&argp, argc, argv, 0, 0, &args); + + if(args.count == 0) + { + fprintf(stderr, "ERROR: count must be larger than 0.\n"); + return 1; + } + + struct llist prime_list; + llist_init(&prime_list); + + { + // initialize the list with 2 + mpz_t tmp; + mpz_init(tmp); + mpz_set_ui(tmp, 2); + llist_add(&prime_list, tmp); + mpz_clear(tmp); + } + + mpz_t aux; + mpz_init(aux); + mpz_set_ui(aux, 3); + while(prime_list.size < args.count) + { + struct llist_item *item = prime_list.first; + int is_prime = 1; + while(item) + { + if(mpz_divisible_p(aux, item->num)) + { + is_prime = 0; + break; + } + item = item->next; + } + if(is_prime) + llist_add(&prime_list, aux); + mpz_add_ui(aux, aux, 2); + } + + printf("The %zu prime is ", prime_list.size); + mpz_out_str(stdout, 10, prime_list.last->num); + + llist_deinit(&prime_list); return 0; }