GNU Octave 7.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
__isprimelarge__.cc
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////
2//
3// Copyright (C) 2021-2022 The Octave Project Developers
4//
5// See the file COPYRIGHT.md in the top-level directory of this
6// distribution or <https://octave.org/copyright/>.
7//
8// This file is part of Octave.
9//
10// Octave is free software: you can redistribute it and/or modify it
11// under the terms of the GNU General Public License as published by
12// the Free Software Foundation, either version 3 of the License, or
13// (at your option) any later version.
14//
15// Octave is distributed in the hope that it will be useful, but
16// WITHOUT ANY WARRANTY; without even the implied warranty of
17// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18// GNU General Public License for more details.
19//
20// You should have received a copy of the GNU General Public License
21// along with Octave; see the file COPYING. If not, see
22// <https://www.gnu.org/licenses/>.
23//
24////////////////////////////////////////////////////////////////////////
25
26#if defined (HAVE_CONFIG_H)
27# include "config.h"
28#endif
29
30#include "defun.h"
31#include "error.h"
32#include "ovl.h"
33
34OCTAVE_NAMESPACE_BEGIN
35
36// This function implements the Schrage technique for modular multiplication.
37// The returned value is equivalent to "mod (a*b, modulus)"
38// but calculated without overflow.
39uint64_t
40safemultiply (uint64_t a, uint64_t b, uint64_t modulus)
41{
42 if (! a || ! b)
43 return 0;
44 else if (b == 1)
45 return a;
46 else if (a == 1)
47 return b;
48 else if (a > b)
49 {
50 uint64_t tmp = a;
51 a = b;
52 b = tmp;
53 }
54
55 uint64_t q = modulus / a;
56 uint64_t r = modulus - q * a;
57 uint64_t term1 = a * (b % q);
58 uint64_t term2 = (r < q) ? r * (b / q) : safemultiply (r, b / q, modulus);
59 return (term1 > term2) ? (term1 - term2) : (term1 + modulus - term2);
60}
61
62// This function returns "mod (a^b, modulus)"
63// but calculated without overflow.
64uint64_t
65safepower (uint64_t a, uint64_t b, uint64_t modulus)
66{
67 uint64_t retval = 1;
68 while (b > 0)
69 {
70 if (b & 1)
71 retval = safemultiply (retval, a, modulus);
72 b >>= 1;
73 a = safemultiply (a, a, modulus);
74 }
75 return retval;
76}
77
78// This function implements a single round of Miller-Rabin primality testing.
79// Returns false if composite, true if pseudoprime for this divisor.
80bool
81millerrabin (uint64_t div, uint64_t d, uint64_t r, uint64_t n)
82{
83 uint64_t x = safepower (div, d, n);
84 if (x == 1 || x == n-1)
85 return true;
86
87 for (uint64_t j = 1; j < r; j++)
88 {
89 x = safemultiply (x, x, n);
90 if (x == n-1)
91 return true;
92 }
93 return false;
94}
95
96// This function uses the Miller-Rabin test to find out whether the input is
97// prime or composite. The input is required to be a scalar 64-bit integer.
98bool
99isprimescalar (uint64_t n)
100{
101 // Fast return for even numbers. n==2 is excluded by the time this function is called.
102 if (! (n & 1))
103 return false;
104
105 // n is now odd. Rewrite n as d * 2^r + 1, where d is odd.
106 uint64_t d = n-1;
107 uint64_t r = 0;
108 while (! (d & 1))
109 {
110 d >>= 1;
111 r++;
112 }
113
114 // Miller-Rabin test with the first 12 primes.
115 // If the number passes all 12 tests, then it is prime.
116 // If it fails any, then it is composite.
117 // The first 12 primes suffice to test all 64-bit integers.
118 if (! millerrabin ( 2, d, r, n)) return false;
119 if (! millerrabin ( 3, d, r, n)) return false;
120 if (! millerrabin ( 5, d, r, n)) return false;
121 if (! millerrabin ( 7, d, r, n)) return false;
122 if (! millerrabin (11, d, r, n)) return false;
123 if (! millerrabin (13, d, r, n)) return false;
124 if (! millerrabin (17, d, r, n)) return false;
125 if (! millerrabin (19, d, r, n)) return false;
126 if (! millerrabin (23, d, r, n)) return false;
127 if (! millerrabin (29, d, r, n)) return false;
128 if (! millerrabin (31, d, r, n)) return false;
129 if (! millerrabin (37, d, r, n)) return false;
130 // If we are all the way here, then it is prime.
131 return true;
132
133 /*
134 Mathematical references for the curious as to why we need only
135 the 12 smallest primes for testing all 64-bit numbers:
136 (1) https://oeis.org/A014233
137 Comment: a(12) > 2^64. Hence the primality of numbers < 2^64 can be
138 determined by asserting strong pseudoprimality to all prime bases <= 37
139 (=prime(12)). Testing to prime bases <=31 does not suffice,
140 as a(11) < 2^64 and a(11) is a strong pseudoprime
141 to all prime bases <= 31 (=prime(11)). - Joerg Arndt, Jul 04 2012
142 (2) https://arxiv.org/abs/1509.00864
143 Strong Pseudoprimes to Twelve Prime Bases
144 Jonathan P. Sorenson, Jonathan Webster
145
146 In addition, a source listed here: https://miller-rabin.appspot.com/
147 reports that all 64-bit numbers can be covered with only 7 divisors,
148 namely 2, 325, 9375, 28178, 450775, 9780504, and 1795265022.
149 There was no peer-reviewed article to back it up though,
150 so this code uses the 12 primes <= 37.
151 */
152
153}
154
155DEFUN (__isprimelarge__, args, ,
156 doc: /* -*- texinfo -*-
157@deftypefn {} {@var{x} =} __isprimelarge__ (@var{n})
158Use the Miller-Rabin test to find out whether the elements of N are prime or
159composite. The input N is required to be a vector or array of 64-bit integers.
160You should call isprime(N) instead of directly calling this function.
161
162@seealso{isprime, factor}
163@end deftypefn */)
164{
165 int nargin = args.length ();
166 if (nargin != 1)
167 print_usage ();
168
169 // This function is intended for internal use by isprime.m,
170 // so the following error handling should not be necessary. But it is
171 // probably good practice for any curious users calling it directly.
172 uint64NDArray vec = args(0).xuint64_array_value
173 ("__isprimelarge__: unable to convert input. Call isprime() instead.");
174
175 boolNDArray retval (vec.dims(), false);
176
177 for (octave_idx_type i = vec.numel() - 1; i >= 0; i--)
178 retval(i) = isprimescalar (vec(i));
179 // Note: If vec(i) <= 37, this function could go into an infinite loop.
180 // That situation does not arise when calling this from isprime.m
181 // but it could arise if the user calls this function directly with low input
182 // or negative input.
183 // But it turns out that adding this validation:
184 // "if (vec(i) <= 37) then raise an error else call isprimescalar (vec(i))"
185 // slows this function down by over 20% for some inputs,
186 // so it is better to leave all the input validation in isprime.m
187 // and not add it here. The function DOCSTRING now explicitly says:
188 // "You should call isprime(N) instead of directly calling this function."
189
190 return ovl (retval);
191}
192
193/*
194%!assert (__isprimelarge__ (41:50), logical ([1 0 1 0 0 0 1 0 0 0]))
195%!assert (__isprimelarge__ (uint64 (12345)), false)
196%!assert (__isprimelarge__ (uint64 (2147483647)), true)
197%!assert (__isprimelarge__ (uint64 (2305843009213693951)), true)
198%!assert (__isprimelarge__ (uint64 (18446744073709551557)), true)
199
200%!assert (__isprimelarge__ ([uint64(12345), uint64(2147483647), uint64(2305843009213693951), uint64(18446744073709551557)]), logical ([0 1 1 1]))
201
202%!error <unable to convert input> (__isprimelarge__ ({'foo'; 'bar'}))
203*/
204
205OCTAVE_NAMESPACE_END
bool isprimescalar(uint64_t n)
bool millerrabin(uint64_t div, uint64_t d, uint64_t r, uint64_t n)
OCTAVE_NAMESPACE_BEGIN uint64_t safemultiply(uint64_t a, uint64_t b, uint64_t modulus)
uint64_t safepower(uint64_t a, uint64_t b, uint64_t modulus)
octave_idx_type numel(void) const
Number of elements in the array.
Definition: Array.h:411
const dim_vector & dims(void) const
Return a const-reference so that dims ()(i) works efficiently.
Definition: Array.h:487
OCTINTERP_API void print_usage(void)
Definition: defun-int.h:72
#define DEFUN(name, args_name, nargout_name, doc)
Macro to define a builtin function.
Definition: defun.h:56
F77_RET_T const F77_DBLE const F77_DBLE F77_DBLE * d
F77_RET_T const F77_DBLE * x
octave_value_list ovl(const OV_Args &... args)
Construct an octave_value_list with less typing.
Definition: ovl.h:211