xref: /netbsd-src/external/lgpl3/gmp/dist/demos/isprime.c (revision 72c7faa4dbb41dbb0238d6b4a109da0d4b236dd4)
1 /* Classify numbers as probable primes, primes or composites.
2    With -q return true if the following argument is a (probable) prime.
3 
4 Copyright 1999, 2000, 2002, 2005, 2012 Free Software Foundation, Inc.
5 
6 This program is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free Software
8 Foundation; either version 3 of the License, or (at your option) any later
9 version.
10 
11 This program is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 
15 You should have received a copy of the GNU General Public License along with
16 this program.  If not, see https://www.gnu.org/licenses/.  */
17 
18 #include <stdlib.h>
19 #include <string.h>
20 #include <stdio.h>
21 
22 #include "gmp.h"
23 
24 char *progname;
25 
26 void
print_usage_and_exit()27 print_usage_and_exit ()
28 {
29   fprintf (stderr, "usage: %s -q nnn\n", progname);
30   fprintf (stderr, "usage: %s nnn ...\n", progname);
31   exit (-1);
32 }
33 
34 int
main(int argc,char ** argv)35 main (int argc, char **argv)
36 {
37   mpz_t n;
38   int i;
39 
40   progname = argv[0];
41 
42   if (argc < 2)
43     print_usage_and_exit ();
44 
45   mpz_init (n);
46 
47   if (argc == 3 && strcmp (argv[1], "-q") == 0)
48     {
49       if (mpz_set_str (n, argv[2], 0) != 0)
50 	print_usage_and_exit ();
51       exit (mpz_probab_prime_p (n, 25) == 0);
52     }
53 
54   for (i = 1; i < argc; i++)
55     {
56       int class;
57       if (mpz_set_str (n, argv[i], 0) != 0)
58 	print_usage_and_exit ();
59       class = mpz_probab_prime_p (n, 25);
60       mpz_out_str (stdout, 10, n);
61       if (class == 0)
62 	puts (" is composite");
63       else if (class == 1)
64 	puts (" is a probable prime");
65       else /* class == 2 */
66 	puts (" is a prime");
67     }
68   exit (0);
69 }
70