gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Java prime check shortest unknown way
- User
Java prime check shortest unknown way
- Assistant
One of the shortest ways to check if a number is prime in Java is to use the following code:
javapublic boolean isPrime(int number) { if (number <= 1) { return false; } for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { return false; } } return true; }Explanation:
- The function
isPrimetakes an integer number as input and returns a boolean value indicating whether the number is prime or not. - The first condition checks if the number is less than or equal to 1. If so, it is not a prime number, and hence,
falseis returned. - The for loop starts from 2 and iterates up to the square root of the number (
Math.sqrt(number)). This is because, if a number is divisible by a factor greater than its square root, the corresponding factor less than its square root would have already been considered in an earlier iteration.
- The function