To find a given input number is prime.,
Iterate each number from 2 to half of input number, and check whether each iteration number divides the input number. (If no number divides, the input number is prime)
We can check whether the number is divisible by using modulo (%) function, so that if number is divisible, then result will be 0, else it will return 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class PrimeNumbers { public static void main(String[] args) { int i, j; boolean isPrime; // loop through all numbers from 1 to 10 for (i = 2; i <= 10; i++) { isPrime = true; // check if the current number is prime for (j = 2; j <= i / 2; j++) { if (i % j == 0) { isPrime = false; break; } } // print the prime number if (isPrime) { System.out.print(i + " "); } } } } |