A prime number is a natural number greater than 1 that has no positive divisors other than
1 and itself.
On the other hand, a composite number is a natural number greater than 1 that is not a
prime number.
For example, 5 is prime, as only 1 and 5 divide it, whereas 6 is composite, since it has the
divisors 2 and 3 in addition to 1 and 6.
Write a java method isPrimeNum that takes the number n, and checks whether the number
is prime or composite. The method should print at the end a message that indicates whether
n is prime or composite.
So is 93 prime or composite ??
Sure! Here's a Java code that implements the `isPrimeNum` method that checks whether a given number `n` is prime or composite:
```java
public class PrimeOrComposite {
public static void isPrimeNum(int n) {
boolean isPrime = true;
if (n <= 1) {
System.out.println(n + " is neither prime nor composite.");
return;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(n + " is a prime number.");
} else {
System.out.println(n + " is a composite number.");
}
}
public static void main(String[] args) {
int num = 6;
isPrimeNum(num);
}
}
```
In this code, we first check if the number `n` is less than or equal to 1. If it is, we print a message indicating that it is neither prime nor composite.
Then, we iterate from 2 to the square root of `n`, checking if `n` is divisible by any number within that range. If it is divisible by any number, we set the `isPrime` variable to false and exit the loop.
Finally, we check the `isPrime` variable to determine whether `n` is prime or composite, and print the corresponding message.
In the `main` method, we call the `isPrimeNum` method with a test value of `6`. You can modify this value to test other numbers.
Sure, here's an implementation of the `isPrimeNum` method in Java:
```java
public class PrimeNumberChecker {
public static void isPrimeNum(int n) {
boolean prime = true;
if (n <= 1) {
prime = false;
}
else {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
prime = false;
break;
}
}
}
if (prime) {
System.out.println(n + " is a prime number.");
}
else {
System.out.println(n + " is a composite number.");
}
}
public static void main(String[] args) {
int number = 9;
isPrimeNum(number);
}
}
```
In this implementation, we define a method `isPrimeNum` that takes an integer `n` as input. The method checks whether `n` is a prime or composite number by iterating from 2 to the square root of `n`. If any number between 2 and the square root of `n` evenly divides `n`, then `n` is not a prime number.
At the end of the method, we print a message indicating whether `n` is prime or composite based on the value of the boolean variable `prime`.
In the `main` method, we call `isPrimeNum` with the number 9 as an example. You can change the value of `number` to any other number to test the method.
I hope this helps! Let me know if you have any further questions.