Skip to content

Better way to check whether a number is prime or not. Update PrimeCheck.java #5258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/com/thealgorithms/maths/PrimeCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ public static boolean isPrime(int n) {
}
return true;
}


// Skip even numbers (except 2) since they are not prime.
// Skip multiples of 3 after checking 3.
// Start checking for factors from 5 and use the 6k ± 1 optimization.
// This is based on the fact that any prime number greater than 3 can be expressed as 6k ± 1.
// This function is more efficient, especially for larger numbers, as it reduces the number of iterations by skipping unnecessary checks.
public static boolean isPrimeNumberOptimised(long number){
if(number <= 1) return false;
if(number <= 3) return true;
for(long i = 5; (i * i) <= number; i += 6){
if(number % i == 0 || number % (i+2) == 0){
return false;
}
}
return true;
}

/**
* *
Expand Down
Loading