Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active August 18, 2018 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/e7dd6981e0241836a2c3f9988a3836a0 to your computer and use it in GitHub Desktop.
Save thmain/e7dd6981e0241836a2c3f9988a3836a0 to your computer and use it in GitHub Desktop.
public class CheckPrimeNumber {
static void naiveMethod(int n){
System.out.print("O(N) Solution : ");
boolean isPrime = true;
for (int i = 2; i <n ; i++) {
if(n%i==0) {
System.out.println("Number " + n +" is not a prime no");
isPrime = false;
break;
}
}
if(isPrime)
System.out.println("Number " + n +" is a prime no");
//Time Complexity: O(N)
}
static void betterMethod(int n){
boolean isPrime = true;
System.out.print("O(N/2) Solution : ");
for (int i = 2; i <=n/2 ; i++) {
if(n%i==0) {
System.out.println("Number " + n +" is not a prime no");
isPrime = false;
break;
}
}
if(isPrime)
System.out.println("Number " + n +" is a prime no");
//Time Complexity: O(N/2) ~ O(N)
}
static void bestMethod(int n){
boolean isPrime = true;
System.out.print("O(√N) Solution : ");
for (int i = 2; i <=Math.sqrt(n) ; i++) {
if(n%i==0) {
System.out.println("Number " + n +" is not a prime no");
isPrime = false;
break;
}
}
if(isPrime)
System.out.println("Number " + n +" is a prime no");
//Time Complexity: O(√N)
}
public static void main(String[] args) {
int n = 13;
naiveMethod(n);
betterMethod(n);
bestMethod(n);
n = 15;
naiveMethod(n);
betterMethod(n);
bestMethod(n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment