2016-12-09 22:02:51 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <signal.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <gmp.h>
|
|
|
|
|
|
|
|
#include "list.h"
|
|
|
|
|
|
|
|
static bool run;
|
|
|
|
void leave();
|
|
|
|
|
|
|
|
int main(void) {
|
2016-12-13 17:09:05 +00:00
|
|
|
puts("Indivisible v0.5\n");
|
2016-12-09 22:02:51 +00:00
|
|
|
|
|
|
|
// Quit on ^C by setting `run = false'
|
|
|
|
run = true;
|
|
|
|
signal(SIGINT, leave);
|
|
|
|
|
|
|
|
// Primes we've found
|
|
|
|
List primes;
|
|
|
|
initList(&primes);
|
|
|
|
|
|
|
|
// The number we're going to be testing for
|
|
|
|
mpz_t num;
|
|
|
|
mpz_init(num);
|
|
|
|
|
|
|
|
// Add 2, a known prime to this list
|
|
|
|
mpz_set_ui(num, 2);
|
|
|
|
addToList(&primes, num);
|
2016-12-10 01:09:34 +00:00
|
|
|
if(mpz_out_str(stdout, 10, num) == 0) {
|
2016-12-09 22:02:51 +00:00
|
|
|
fprintf(stderr, "Could not print to `stdout'!\n");
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
printf("\n");
|
|
|
|
mpz_add_ui(num, num, 1);
|
|
|
|
|
2016-12-10 13:46:51 +00:00
|
|
|
// Variable for half `num'
|
|
|
|
mpz_t halfNum;
|
|
|
|
mpz_init(halfNum);
|
|
|
|
|
2016-12-09 22:02:51 +00:00
|
|
|
do {
|
2016-12-10 13:46:51 +00:00
|
|
|
// Calculate half of `num'
|
|
|
|
mpz_fdiv_q_ui(halfNum, num, 2);
|
2016-12-09 22:02:51 +00:00
|
|
|
// Loop through found primes
|
2016-12-14 13:13:32 +00:00
|
|
|
for(size_t i = 0; i < primes.end; ++i) {
|
2016-12-13 17:05:02 +00:00
|
|
|
if(mpz_cmp(primes.list[i], halfNum) > 0) break;
|
2016-12-09 22:02:51 +00:00
|
|
|
// If `num' is divisible by a prime then go to the next number
|
2016-12-10 10:20:01 +00:00
|
|
|
if(mpz_divisible_p(num, primes.list[i]) != 0)
|
|
|
|
goto nextPrime;
|
2016-12-09 22:02:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// `num' is a prime so we add it to the list and print it
|
|
|
|
addToList(&primes, num);
|
2016-12-10 13:46:51 +00:00
|
|
|
if(mpz_out_str(stdout, 10, num) == 0) {
|
2016-12-09 22:02:51 +00:00
|
|
|
fprintf(stderr, "Could not print to `stdout'!\n");
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
printf("\n");
|
|
|
|
|
|
|
|
nextPrime:
|
|
|
|
// Add 2 (skip even numbers since they're all divisible by 2)
|
|
|
|
mpz_add_ui(num, num, 2);
|
2016-12-10 13:46:51 +00:00
|
|
|
} while(run);
|
2016-12-09 22:02:51 +00:00
|
|
|
|
2016-12-10 13:46:51 +00:00
|
|
|
// Clear GMP variables
|
|
|
|
mpz_clear(halfNum);
|
2016-12-10 10:20:01 +00:00
|
|
|
mpz_clear(num);
|
2016-12-09 22:02:51 +00:00
|
|
|
// Deinitialize the list
|
|
|
|
deInitList(&primes);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void leave() {
|
2016-12-10 16:11:21 +00:00
|
|
|
puts("Exiting...\n");
|
2016-12-09 22:02:51 +00:00
|
|
|
run = false;
|
|
|
|
}
|