Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <math.h>
- #include <gmp.h>
- int main(int argc, char *argv[]) {
- mpz_t number, num2, divisor, starter; //num2 is converted into a double to act as the counter
- long double counter = 0, final = 2;
- int flag = 0, calcs = 1;
- time_t start, end;
- mpz_init (number);
- mpz_init (num2);
- mpz_init (divisor);
- mpz_init (starter);
- printf("Please enter a number.\n");
- mpz_inp_str (number, stdin, 10);
- flag = mpz_cmp_si(number, 2);
- if (flag < 1) {
- printf("Error: Number must be greater than 2. Please run the program and try again.\n");
- return EXIT_FAILURE;
- }
- flag = 0;
- mpz_sqrt (num2, number);
- counter = mpz_get_d (num2);
- mpz_set_ui (starter, 2);
- gmp_printf("Checking %Zd for primality.\nTesting divisibility with all numbers up to %LF\n\nPlease wait...\n", number, counter);
- start = time(NULL);
- do {
- mpz_mod (divisor, number, starter);
- flag = mpz_cmp_si(divisor, 0);
- if (flag == 0) {
- end = time(NULL);
- gmp_printf("%Zd is divisible by %Zd.\n\nOperation took approximately %ld seconds\n", number, starter, (end - start));
- return EXIT_SUCCESS;
- }
- else {
- final += 1;
- mpz_add_ui (starter, starter, 1);
- if (fmod(final, 10000000) == 0) {
- printf("%d0 million calculations and counting...\n", calcs);
- calcs++;
- }
- continue;
- }
- } while (final < counter);
- end = time(NULL);
- gmp_printf("%Zd is prime.\n\nOperation took approximately %ld seconds\n", number, (end - start));
- mpz_clear (number);
- mpz_clear (num2);
- mpz_clear (divisor);
- mpz_clear (starter);
- return 0;
- }
- //This program cannot check numbers greater than 8.1 * 10^31 accurately
- //Compile on linux with this command: gcc file.c -o file -lgmp -lm -O3
Advertisement
Add Comment
Please, Sign In to add comment