Prime numbers are numbers that have only 2 factors. The two factors are 1 and themselves.
For example number = 6
6: 1,2,3,6 => 6 is not a prime
3: 1,3 => 3 is a prime number (3 is divisible by 1 and 3 only)
public class Prime {
public static void main(String[] args) {
int n = 3,count=0;
for(int i=1;i<=n;i++){
if(n%i==0){
count++;
}
}
if(count==2){
System.out.println("Prime");
}
else{
System.out.println("Not a prime");
}
}
}
Prime
Here we can also optimize the code by starting the loop from 2 and without using the count variable.
i=2
3: 3
public class Prime {
public static void main(String[] args) {
int n = 6;
for(int i=2;i<n;i++){
if(n%i==0){
System.out.println("Not a prime");
System.exit(0);
}
}
System.out.println("Prime");
}
}
Not a prime
Take n = 6;
i range from 2 to 5(n-1)
if (n%i ==0)
Not a prime
exit from the code
None of the i values divides the n then it is prime.
Better Approach:
for example number 36
repeating the loop from 2 to 36 will take more time time limit also exceed in coding challenges
better to follow this
36 = 1 * 36
36 = 2 * 18
36 = 3 *12
36 = 4 * 9
36 = 6 * 6
36 = 9 * 4
36 = 12 * 3
36 = 18 * 2
36 = 36 * 1
the square root of 36 is 6
after the 6 * 6 multiplication, all are repeated twice
so only repeat the loop to root(n)
root(36) = 6
public class Prime {
public static void main(String[] args) {
int n = 18;
double val = Math.round(Math.sqrt(n));
for(int i=2;i<=val;i++){
if(n%i==0){
System.out.println("Not a prime");
System.exit(0);
}
}
System.out.println("Prime");
}
}
Not a prime
OR
we can write this way also
public class Prime {
public static void main(String[] args) {
int n = 29;
for(int i=2;i*i<n;i++){
if(n%i==0){
System.out.println("Not a prime");
System.exit(0);
}
}
System.out.println("Prime");
}
}
Prime