A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 5 is prime, as only 1 and 5 divide it, whereas 6 is not, since it has the divisors 2 and 3 in addition to 1 and 6.
any integer number n.
NO for not a prime number (a composite number) and YES for a prime number.
Look at the definition of a prime number definition. A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 5 is prime, as only 1 and 5 divide it.
Here, we use for loop with initial value 2. Why start with 2? It is because integer 1 is the divisor for all integers (any numbers can divide with 1).
For example, if num is 5:
So, 5 is a prime number because 5 only can be divided by number 1 and 5 (itself) only.
import java.util.Scanner;
public class MyPrimeNumCheck {
public static void main(String a[]){
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
boolean isPrime = true;
for(int i=2; i<=num/2; i++){
if(num % i == 0){
isPrime = false;
}
}
if (isPrime)
System.out.println("YES"); // if isPrime == true
else
System.out.println("NO");
}
}
The output will look like this:
2
YES
Exercise
Write a program to display the prime numbers that less than 50.
Your output should look like this:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47