/src/gettext-0.26/gettext-tools/libgettextpo/next-prime.c
Line | Count | Source |
1 | | /* Finding the next prime >= a given small integer. |
2 | | Copyright (C) 1995-2025 Free Software Foundation, Inc. |
3 | | |
4 | | This file is free software: you can redistribute it and/or modify |
5 | | it under the terms of the GNU Lesser General Public License as |
6 | | published by the Free Software Foundation; either version 2.1 of the |
7 | | License, or (at your option) any later version. |
8 | | |
9 | | This file is distributed in the hope that it will be useful, |
10 | | but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
12 | | GNU Lesser General Public License for more details. |
13 | | |
14 | | You should have received a copy of the GNU Lesser General Public License |
15 | | along with this program. If not, see <https://www.gnu.org/licenses/>. */ |
16 | | |
17 | | #include <config.h> |
18 | | |
19 | | /* Specification. */ |
20 | | #include "next-prime.h" |
21 | | |
22 | | #include <stdint.h> /* for SIZE_MAX */ |
23 | | |
24 | | /* Return true if CANDIDATE is a prime number or 1. |
25 | | CANDIDATE should be an odd number >= 1. */ |
26 | | static bool _GL_ATTRIBUTE_CONST |
27 | | is_prime (size_t candidate) |
28 | 11.5k | { |
29 | 11.5k | size_t divisor = 3; |
30 | 11.5k | size_t square = divisor * divisor; |
31 | | |
32 | 11.5k | for (;;) |
33 | 23.2k | { |
34 | 23.2k | if (square > candidate) |
35 | 11.4k | return true; |
36 | 11.7k | if ((candidate % divisor) == 0) |
37 | 17 | return false; |
38 | | /* Increment divisor by 2. */ |
39 | 11.7k | divisor++; |
40 | 11.7k | square += 4 * divisor; |
41 | 11.7k | divisor++; |
42 | 11.7k | } |
43 | 11.5k | } |
44 | | |
45 | | size_t _GL_ATTRIBUTE_CONST |
46 | | next_prime (size_t candidate) |
47 | 11.4k | { |
48 | 11.4k | #if !defined IN_LIBGETTEXTLIB |
49 | | /* Skip small primes. */ |
50 | 11.4k | if (candidate < 10) |
51 | 0 | candidate = 10; |
52 | 11.4k | #endif |
53 | | |
54 | | /* Make it definitely odd. */ |
55 | 11.4k | candidate |= 1; |
56 | | |
57 | 11.5k | while (SIZE_MAX != candidate && !is_prime (candidate)) |
58 | 17 | candidate += 2; |
59 | | |
60 | 11.4k | return candidate; |
61 | 11.4k | } |