Chapter: Miscellaneous Last Updated: 08-09-2017 16:30:08 UTC

Program:

` ````
/* ............... START ............... */
public class JavaNumberIsPrimeOrNot {
public static void main(String[] args) {
int num = 17;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
/* ............... END ............... */
```

Output

17 is a prime number.

Notes:

- A prime number is a number which is divisible by only two numbers: 1 and itself.
- In the above program, for loop is used to determine if the given number num is prime or not.
- Inside the for loop, we check if the number is divisible by any number in the given range (2..num/2). If it is, flag is set to true and we break out of the loop. This determines num is not a prime number.
- If num isn't divisible by any number, flag is false and num is a prime number.

Tags

Check Whether Number Is Prime Or Not, Java, Interview