To find prime numbers in Java, you can use a loop to iterate over a range of numbers and use the modulo operator (%
) to check if each number is prime.
Here's an example of how to find prime numbers in Java:
int start = 2; int end = 100; for (int i = start; i <= end; i++) { boolean isPrime = true; for (int j = 2; j < i; j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) { System.out.println(i + " is prime"); } }
In the above example, a loop is used to iterate over the range of numbers from start
to end
. For each number in the range, a second loop is used to check if the number is divisible by any other numbers between 2 and itself.
If the number is divisible by any other number, it is not prime and the isPrime
variable is set to false
. If the number is not divisible by any other number, it is prime and the isPrime
variable remains true
.
After the inner loop completes, the isPrime
variable is checked. If it is true
, the number is prime and a message is printed to the console stating that the number is prime. If it is false
, the number is not prime and no message is printed.
Keep in mind that this example only works for positive integers. If you need to handle negative integers or non-integer values, you may need to use a different approach.