If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check for a prime number and find the next prime number in Java, you can create separate methods for each task. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Here's an example of how to do this:
javaCopy code
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
int nextPrime = findNextPrime(num);
System.out.println("Next prime number after " + num + " is " + nextPrime + ".");
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// Method to find the next prime number after a given number
public static int findNextPrime(int num) {
int nextNum = num + 1;
while (true) {
if (isPrime(nextNum)) {
return nextNum;
}
nextNum++;
}
}
}
In this example, we have two methods: isPrime()
to check if a number is prime and findNextPrime()
to find the next prime number after a given number.
isPrime(int num)
:num
as input and returns a boolean value indicating whether the number is prime or not.num
and checks if any of these numbers divide num
without leaving a remainder. If any such divisor is found, the number is not prime.findNextPrime(int num)
:num
as input and returns the next prime number after num
.nextNum
to num + 1
.nextNum
is prime using the isPrime()
method. If it is prime, it returns nextNum
; otherwise, it increments nextNum
and repeats the process.By using these methods, you can easily check if a number is prime and find the next prime number in Java.
Comments: 0