greeter

prime number checker

Jun 20th, 2013
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <time.h>
  5.  
  6. int main(int argc, char *argv[]) {
  7.     double test = 0, divisor = 0;
  8.     long unsigned int counter = 2, max = 0;
  9.     time_t start = time(NULL), end;
  10.     if (argc == 2) {
  11.         test = atof(argv[1]);
  12.         if (test == 0) {
  13.             printf("Error: Invalid input detected. Quitting...\n\nThis may be caused by not entering a number, or by entering the number 0.\nPlease re-run the program with valid input.\n");
  14.             return 0;
  15.         }
  16.         if (test < 0) {
  17.             printf("Error: Number must be greater than 0\n");
  18.             return 0;
  19.         }
  20.         printf("Will wind up checking value %lf\nPlease wait...\n", test);
  21.         max = (sqrt(test) + 1); //one is added to ensure rounding down does not cause errors in the result
  22.         printf("Testing divisibility with all numbers up to: %ld\n\n", max);
  23.         do {
  24.             divisor = fmod(test, counter);
  25.             if (divisor == 0) {
  26.                 printf("%lf is divisible by %ld\n", test, counter);
  27.                 end = time(NULL);
  28.                 printf("Calculation took approximately %d seconds.\n", (end - start));
  29.                 break;
  30.             }
  31.             else {
  32.                 counter++;
  33.                 continue;
  34.             }
  35.         } while (counter < max);
  36.         if (counter >= max) {
  37.             printf("%lf is prime\n", test);
  38.             end = time(NULL);
  39.             printf("Calculation took  approximately %d seconds.\n", (end - start));
  40.         }
  41.         return 0;
  42.     }
  43.     else {
  44.         printf("Usage: %s [number]\n\n[number] represents the number you wish to check.\nNote: Number MUST be greater than 0\n", argv[0]);
  45.         return 0;
  46.     }
  47. }
  48.  
  49. /* This prime number checker can check numbers up to 16 digits in length. Be careful as beyond that point it seems to lose accuracy. I'm not sure why this is, but will work on improving it */
Advertisement
Add Comment
Please, Sign In to add comment