Ad
Code
Diff
  • import java.util.stream.IntStream;
    
    // runs in < 300 ms
    public class Primes {
      public static boolean isAPrime(int num) {
        if (num % 2 == 0) return num == 2;
        int maxtest = (int) Math.sqrt(num);
        return IntStream.iterate(3, i -> i <= maxtest, i -> 2 + i).noneMatch(divider -> (num % divider) == 0);
      }
    }
    • import java.util.stream.IntStream;
    • // runs in < 300 ms
    • public class Primes {
    • public static boolean isAPrime(int num) {
    • return IntStream.range(2, (num/2 +1)).noneMatch(divider -> (num % divider) == 0);
    • if (num % 2 == 0) return num == 2;
    • int maxtest = (int) Math.sqrt(num);
    • return IntStream.iterate(3, i -> i <= maxtest, i -> 2 + i).noneMatch(divider -> (num % divider) == 0);
    • }
    • }
Code
Diff
  • // this is pretty fast: < 100 ms
    public class Primes {
      public static boolean isAPrime(int number) {
        if (number < 2 || (number % 2 == 0 && number != 2)) return false;
        int endvalue = (int) Math.sqrt(number);
        for (int i = 3; i <= endvalue; i += 2) {
          if (number % i == 0) return false;
        }
        return true;
      }
    }
    • // this is pretty fast: < 100 ms
    • public class Primes {
    • public static boolean isAPrime(int number) {
    • if (number < 2 || (number % 2 == 0 && number != 2)) return false;
    • for (int i = 3; i*i <= number; i += 2) {
    • int endvalue = (int) Math.sqrt(number);
    • for (int i = 3; i <= endvalue; i += 2) {
    • if (number % i == 0) return false;
    • }
    • return true;
    • }
    • }
Code
Diff
  • public class Primes {
      public static boolean isAPrime(int number) {
        if (number < 2 || (number % 2 == 0 && number != 2)) return false;
        for (int i = 3; i*i <= number; i += 2) {
          if (number % i == 0) return false;
        }
        return true;
      }
    }
    • public class Primes {
    • public static boolean isAPrime(int number) {
    • if(number > 1 && number == 2) return true; //1 is not a prime number by definition
    • else {
    • for(int i = 3; i*i < number; i +=2) {
    • if (number % i == 0) return false;
    • }
    • if (number < 2 || (number % 2 == 0 && number != 2)) return false;
    • for (int i = 3; i*i <= number; i += 2) {
    • if (number % i == 0) return false;
    • }
    • return true;
    • }
    • }