HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Efficiently determining if a number is prime

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
primenumberefficientlydetermining

Problem

Is this the most efficient way to find if a number is prime? I can't think of a better way and it seems to run pretty quickly.

public boolean primes(int num){
    for(int i = 2; i < num; i++){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
   return true; 
}

Solution

A faster method would be to skip all even numbers and only try up to the square root of the number.

public static boolean isPrime(int num){
    if ( num > 2 && num%2 == 0 ) {
        System.out.println(num + " is not prime");
        return false;
    }
    int top = (int)Math.sqrt(num) + 1;
    for(int i = 3; i < top; i+=2){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
    return true; 
}

Code Snippets

public static boolean isPrime(int num){
    if ( num > 2 && num%2 == 0 ) {
        System.out.println(num + " is not prime");
        return false;
    }
    int top = (int)Math.sqrt(num) + 1;
    for(int i = 3; i < top; i+=2){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
    return true; 
}

Context

StackExchange Code Review Q#24704, answer score: 21

Revisions (0)

No revisions yet.