To check if a number is prime in Java, you can use the following approach:
public static boolean isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; }
This function uses a loop to check if the number n
is divisible by any number between 2 and the square root of n
. If n
is divisible by any of these numbers, it returns false
because n
is not a prime number. If n
is not divisible by any of these numbers, it returns true
because n
is a prime number.
Here is an example of how to use this function:
System.out.println(isPrime(2)); // Outputs true System.out.println(isPrime(3)); // Outputs true System.out.println(isPrime(4)); // Outputs false System.out.println(isPrime(5)); // Outputs true System.out.println(isPrime(6)); // Outputs false
In this example, the function isPrime()
is called with the numbers 2, 3, 4, 5, and 6 as arguments. It returns true
for the prime numbers 2 and 3, and false
for the non-prime numbers 4, 5, and 6.
Note that this function has a time complexity of O(√n), which means it becomes slower as the number n
gets larger. For large numbers, you may need to use a more efficient algorithm to check if a number is prime.
For more information on prime numbers and algorithms for checking if a number is prime, you can refer to online resources or textbooks on mathematics or computer science.