109 lines
1.8 KiB
C
109 lines
1.8 KiB
C
#define _POSIX_C_SOURCE 199309L
|
|
|
|
#include <time.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <limits.h>
|
|
|
|
#include "args.h"
|
|
#include "common.h"
|
|
#include "methods.h"
|
|
|
|
void show_help(char* argv0)
|
|
{
|
|
fprintf(stderr,
|
|
"Usage: %s range [args]\n"
|
|
" Check primes from 0 to range (Maximum %lu)\n"
|
|
"\n"
|
|
"Args:\n"
|
|
" -p, --print Print primes found\n",
|
|
argv0,
|
|
ULONG_MAX
|
|
);
|
|
}
|
|
|
|
int main(int argc, char** argv)
|
|
{
|
|
if(argc <= 1)
|
|
{
|
|
show_help(argv[0]);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
_Args args;
|
|
init_args(&args);
|
|
if(!parse_args(argc, argv, &args))
|
|
{
|
|
show_help(argv[0]);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
unsigned long primes_max = strtoul(argv[1], NULL, 0);
|
|
if(primes_max == 0)
|
|
{
|
|
show_help(argv[0]);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
_Bool *primes = malloc(SIZE);
|
|
if(primes == NULL)
|
|
{
|
|
perror("malloc");
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
for(unsigned long i = 0; i < primes_max; ++i)
|
|
{
|
|
primes[i] = 1;
|
|
}
|
|
primes[0] = 0;
|
|
primes[1] = 0;
|
|
|
|
struct timespec begin_primes;
|
|
struct timespec end_primes;
|
|
int ret = eratosthenes(primes, primes_max, &begin_primes);
|
|
if(ret == -1)
|
|
{
|
|
free(primes);
|
|
perror("clock_gettime");
|
|
return EXIT_FAILURE;
|
|
}
|
|
ret = clock_gettime(CLOCK_MONOTONIC_RAW, &end_primes);
|
|
if(ret == -1)
|
|
{
|
|
free(primes);
|
|
perror("clock_gettime");
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
|
|
if(args.printing)
|
|
{
|
|
for(unsigned long primes_indx = 0; primes_indx < primes_max; ++primes_indx)
|
|
if(primes[primes_indx])
|
|
/* TODO: optimise printing */
|
|
printf("%lu\n", primes_indx);
|
|
}
|
|
|
|
unsigned long prime_count = 0;
|
|
for(unsigned long i = 0; i < primes_max; ++i)
|
|
{
|
|
if(primes[i])
|
|
{
|
|
++prime_count;
|
|
}
|
|
}
|
|
|
|
struct timespec delta_primes;
|
|
get_timespec_delta(&delta_primes, &begin_primes, &end_primes);
|
|
printf("Counted %lu primes\nCalculation took: %li.%09lis\n",
|
|
prime_count,
|
|
delta_primes.tv_sec,
|
|
delta_primes.tv_nsec
|
|
);
|
|
|
|
free(primes);
|
|
return EXIT_SUCCESS;
|
|
}
|
|
|