> 2025-07-15 Bruno Haible <br...@clisp.org> > > next-prime tests: Update unit test after last change. > * tests/test-next-prime.c (main): Allow either behaviour.
Oops. It turns out that - is_prime (3) returns false, leading to next_prime (3) = 5. - the unit test fails because next_prime (1) = 1. This fixes it. 2025-07-19 Bruno Haible <br...@clisp.org> next-prime: Tweaks for GNU gettext. * lib/next-prime.c (is_prime): Change so that is_prime (3) returns true. * tests/test-next-prime.c (main): Allow next_prime (1) to be 1. diff --git a/lib/next-prime.c b/lib/next-prime.c index 58630db9b0..9aa3264f31 100644 --- a/lib/next-prime.c +++ b/lib/next-prime.c @@ -21,22 +21,25 @@ #include <stdint.h> /* for SIZE_MAX */ -/* Return true if CANDIDATE is a prime number. CANDIDATE should be an odd - number at least equal to 11. */ +/* Return true if CANDIDATE is a prime number or 1. + CANDIDATE should be an odd number >= 1. */ static bool _GL_ATTRIBUTE_CONST is_prime (size_t candidate) { size_t divisor = 3; size_t square = divisor * divisor; - while (square < candidate && (candidate % divisor)) + for (;;) { + if (square > candidate) + return true; + if ((candidate % divisor) == 0) + return false; + /* Increment divisor by 2. */ divisor++; square += 4 * divisor; divisor++; } - - return (candidate % divisor ? true : false); } size_t _GL_ATTRIBUTE_CONST diff --git a/tests/test-next-prime.c b/tests/test-next-prime.c index b74257ae83..a5a2e9133c 100644 --- a/tests/test-next-prime.c +++ b/tests/test-next-prime.c @@ -26,8 +26,9 @@ int main () { - ASSERT (next_prime (1) >= 3 && next_prime (1) <= 11); + ASSERT (next_prime (1) >= 1 && next_prime (1) <= 11); ASSERT (next_prime (3) >= 3 && next_prime (3) <= 11); + ASSERT (next_prime (5) >= 5 && next_prime (5) <= 11); ASSERT (next_prime (7) >= 7 && next_prime (7) <= 11); ASSERT (next_prime (10) == 11); ASSERT (next_prime (11) == 11);