Primes { public static int nextPrime(int n) { if (n < 0) { throw new MathIllegalArgumentException(LocalizedFormats.NUMBER_TOO_SMALL, n, 0); } if (n == 2) { return 2; } n |= 1; if (n == 1) { return 2; } if (isPrime(n)) { return n; } final int rem = n % 3; if (0 == rem) { n += 2; } else if (1 == rem) { n += 4; } while (true) { if (isPrime(n)) { return n; } n += 2; if (isPrime(n)) { return n; } n += 4; } } private  Primes(); static boolean isPrime(int n); static int nextPrime(int n); static List<Integer> primeFactors(int n);  }
@Test public void testNextPrime() { Assert.assertEquals(2, Primes.nextPrime(0)); Assert.assertEquals(2, Primes.nextPrime(1)); Assert.assertEquals(2, Primes.nextPrime(2)); Assert.assertEquals(3, Primes.nextPrime(3)); Assert.assertEquals(5, Primes.nextPrime(4)); Assert.assertEquals(5, Primes.nextPrime(5)); for (int i = 0; i < SmallPrimes.PRIMES.length - 1; i++) { for (int j = SmallPrimes.PRIMES[i] + 1; j <= SmallPrimes.PRIMES[i + 1]; j++) { Assert.assertEquals(SmallPrimes.PRIMES[i+1], Primes.nextPrime(j)); } } Assert.assertEquals(25325981, Primes.nextPrime(25325981)); for (int i = 25325981 + 1; i <= 25326023; i++) { Assert.assertEquals(25326023, Primes.nextPrime(i)); } Assert.assertEquals(Integer.MAX_VALUE, Primes.nextPrime(Integer.MAX_VALUE - 10)); Assert.assertEquals(Integer.MAX_VALUE, Primes.nextPrime(Integer.MAX_VALUE - 1)); Assert.assertEquals(Integer.MAX_VALUE, Primes.nextPrime(Integer.MAX_VALUE)); assertNextPrimeException(Integer.MIN_VALUE, new MathIllegalArgumentException(LocalizedFormats.NUMBER_TOO_SMALL,Integer.MIN_VALUE,0)); assertNextPrimeException(-1, new MathIllegalArgumentException(LocalizedFormats.NUMBER_TOO_SMALL,-1,0)); assertNextPrimeException(-13, new MathIllegalArgumentException(LocalizedFormats.NUMBER_TOO_SMALL,-13,0)); }