Skip to content

Instantly share code, notes, and snippets.

@scaffeinate
Created January 11, 2019 05:30
Show Gist options
  • Save scaffeinate/62aec329f7b23717f115d5c11808b3eb to your computer and use it in GitHub Desktop.
Save scaffeinate/62aec329f7b23717f115d5c11808b3eb to your computer and use it in GitHub Desktop.
public static int isPrime(int x) {
if(x <= 2) return 1;
int num = 2, k = 0, sqrt = (int) Math.sqrt(x);
boolean[] arr = new boolean[x-1];
while(num <= sqrt) {
if(arr[num-2]) {
num++;
continue;
}
int mul = 2;
while((k = (num * mul)) <= x) {
if(!arr[k-2]) {
arr[k-2] = true;
}
mul++;
}
num++;
}
for(int i = 0; i < arr.length && arr[x-2]; i++) {
if(!arr[i] && x % (i+2) == 0) {
return i+2;
}
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment