greeter

a better prime number checker

Jan 1st, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <math.h>
  5. #include <gmp.h>
  6.  
  7. int main(int argc, char *argv[]) {
  8.     mpz_t number, num2, divisor, starter; //num2 is converted into a double to act as the counter
  9.     long double counter = 0, final = 2;
  10.     int flag = 0, calcs = 1;
  11.     time_t start, end;
  12.     mpz_init (number);
  13.     mpz_init (num2);
  14.     mpz_init (divisor);
  15.     mpz_init (starter);
  16.     printf("Please enter a number.\n");
  17.     mpz_inp_str (number, stdin, 10);
  18.     flag = mpz_cmp_si(number, 2);
  19.     if (flag < 1) {
  20.         printf("Error: Number must be greater than 2. Please run the program and try again.\n");
  21.         return EXIT_FAILURE;
  22.     }
  23.     flag = 0;
  24.     mpz_sqrt (num2, number);
  25.     counter = mpz_get_d (num2);
  26.     mpz_set_ui (starter, 2);
  27.     gmp_printf("Checking %Zd for primality.\nTesting divisibility with all numbers up to %LF\n\nPlease wait...\n", number, counter);
  28.     start = time(NULL);
  29.     do {
  30.         mpz_mod (divisor, number, starter);
  31.         flag = mpz_cmp_si(divisor, 0);
  32.         if (flag == 0) {
  33.             end = time(NULL);
  34.             gmp_printf("%Zd is divisible by %Zd.\n\nOperation took approximately %ld seconds\n", number, starter, (end - start));
  35.             return EXIT_SUCCESS;
  36.         }
  37.         else {
  38.             final += 1;
  39.             mpz_add_ui (starter, starter, 1);
  40.             if (fmod(final, 10000000) == 0) {
  41.                 printf("%d0 million calculations and counting...\n", calcs);
  42.                 calcs++;
  43.             }
  44.             continue;
  45.         }
  46.     } while (final < counter);
  47.     end = time(NULL);
  48.     gmp_printf("%Zd is prime.\n\nOperation took approximately %ld seconds\n", number, (end - start));
  49.     mpz_clear (number);
  50.     mpz_clear (num2);
  51.     mpz_clear (divisor);
  52.     mpz_clear (starter);
  53.     return 0;
  54. }
  55.  
  56.  
  57. //This program cannot check numbers greater than 8.1 * 10^31 accurately
  58. //Compile on linux with this command: gcc file.c -o file -lgmp -lm -O3
Advertisement
Add Comment
Please, Sign In to add comment