lots of exercises in java... from https://github.com/exercism/java

PrimeCalculator.java 790B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import java.util.stream.IntStream;
  2. public final class PrimeCalculator {
  3. public int nth(int nth) {
  4. if (nth < 1) {
  5. throw new IllegalArgumentException();
  6. }
  7. int primesFound = 0;
  8. int possiblePrime = 1;
  9. while (primesFound < nth) {
  10. possiblePrime++;
  11. if (isPrime(possiblePrime)) {
  12. primesFound++;
  13. }
  14. }
  15. return possiblePrime;
  16. }
  17. private boolean isPrime(int n) {
  18. if (n == 1) {
  19. return false;
  20. }
  21. if (n == 2) {
  22. return true;
  23. }
  24. boolean divisible = IntStream
  25. .rangeClosed(2, (int) Math.ceil(Math.sqrt(n)))
  26. .anyMatch((int i) -> n % i == 0);
  27. return !divisible;
  28. }
  29. }