xref: /netbsd-src/external/lgpl3/gmp/dist/tests/mpz/t-pprime_p.c (revision 212397c69a103ae7e5eafa8731ddfae671d2dee7)
1 /* Exercise mpz_probab_prime_p.
2 
3 Copyright 2002 Free Software Foundation, Inc.
4 
5 This file is part of the GNU MP Library test suite.
6 
7 The GNU MP Library test suite is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 3 of the License,
10 or (at your option) any later version.
11 
12 The GNU MP Library test suite is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
15 Public License for more details.
16 
17 You should have received a copy of the GNU General Public License along with
18 the GNU MP Library test suite.  If not, see http://www.gnu.org/licenses/.  */
19 
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include "gmp.h"
23 #include "gmp-impl.h"
24 #include "tests.h"
25 
26 
27 /* Enhancements:
28 
29    - Test some big primes don't come back claimed to be composite.
30    - Test some big composites don't come back claimed to be certainly prime.
31    - Test some big composites with small factors are identified as certainly
32      composite.  */
33 
34 
35 /* return 1 if prime, 0 if composite */
36 int
37 isprime (long n)
38 {
39   long  i;
40 
41   n = ABS(n);
42 
43   if (n < 2)
44     return 0;
45   if (n == 2)
46     return 1;
47   if ((n & 1) == 0)
48     return 0;
49 
50   for (i = 3; i < n; i++)
51     if ((n % i) == 0)
52       return 0;
53 
54   return 1;
55 }
56 
57 void
58 check_one (mpz_srcptr n, int want)
59 {
60   int  got;
61 
62   got = mpz_probab_prime_p (n, 25);
63 
64   /* "definitely prime" is fine if we only wanted "probably prime" */
65   if (got == 2 && want == 1)
66     want = 2;
67 
68   if (got != want)
69     {
70       printf ("mpz_probab_prime_p\n");
71       mpz_trace ("  n    ", n);
72       printf    ("  got =%d", got);
73       printf    ("  want=%d", want);
74       abort ();
75     }
76 }
77 
78 void
79 check_pn (mpz_ptr n, int want)
80 {
81   check_one (n, want);
82   mpz_neg (n, n);
83   check_one (n, want);
84 }
85 
86 /* expect certainty for small n */
87 void
88 check_small (void)
89 {
90   mpz_t  n;
91   long   i;
92 
93   mpz_init (n);
94 
95   for (i = 0; i < 300; i++)
96     {
97       mpz_set_si (n, i);
98       check_pn (n, isprime (i));
99     }
100 
101   mpz_clear (n);
102 }
103 
104 int
105 main (void)
106 {
107   tests_start ();
108 
109   check_small ();
110 
111   tests_end ();
112   exit (0);
113 }
114