Primes { public static int closestPrimeTo(int n) { if (n <= 1) { return 1; } else { int i = Arrays.binarySearch(PRIMES, n); if (i < 0) { i = -i - 1; if (i >= PRIMES.length) { return largestPrime(); } else { int nextPrime = PRIMES[i]; int previousPrime = i > 0 ? PRIMES[i - 1] : 1; return nextPrime - n > n - previousPrime ? previousPrime : nextPrime; } } else { return PRIMES[i]; } } }  static int nthPrime(int i); static int largestPrime(); static int closestPrimeTo(int n);  }
@Test public void shouldReturnOneForClosestPrimesToOneAndBelow() { assertThat(Primes.closestPrimeTo(1), is(1)); assertThat(Primes.closestPrimeTo(0), is(1)); assertThat(Primes.closestPrimeTo(-1), is(1)); }
@Test public void shouldReturnPrimeForClosestOfAPrime() { assertThat(Primes.closestPrimeTo(2), is(2)); assertThat(Primes.closestPrimeTo(3), is(3)); assertThat(Primes.closestPrimeTo(5), is(5)); assertThat(Primes.closestPrimeTo(7), is(7)); }
@Test public void shouldReturnClosestPrimes() { assertThat(Primes.closestPrimeTo(4), is(5)); assertThat(Primes.closestPrimeTo(6), is(7)); assertThat(Primes.closestPrimeTo(8), is(7)); assertThat(Primes.closestPrimeTo(9), is(11)); assertThat(Primes.closestPrimeTo(10), is(11)); assertThat(Primes.closestPrimeTo(32), is(31)); }