Basic prime calculator.

This commit is contained in:
Nicolás Ortega Froysa 2018-10-18 14:56:15 +02:00
parent bd3181a1a0
commit eaa238a900
No known key found for this signature in database
GPG Key ID: FEC70E3BAE2E69BF
2 changed files with 89 additions and 2 deletions

View File

@ -21,3 +21,41 @@
#ifndef VERSION
# define VERSION "version"
#endif
/* argp variables */
const char *argp_program_version = VERSION;
const char *argp_program_bug_address = "<nortega@themusicinnoise.net>";
/* argp options */
static char desc[] = "A parallelized prime number generator.";
/*static char args_doc[] = "--count=<number> [--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 };

View File

@ -17,11 +17,60 @@
*/
#include <stdio.h>
#include <stdlib.h>
#include <argp.h>
#include <gmp.h>
#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;
}