DEV Community

MOHAMED ABDULLAH
MOHAMED ABDULLAH

Posted on

prime numbers in java

A prime number is a number greater than 1 that has only two factors 1 and itself.

For example:

5 is prime → factors: 1, 5

6 is not prime → factors: 1, 2, 3, 6

a Java program to print whether each number from 150 to 300 is a prime number or not.

public class Numbers {

// Method to check if a number is prime
public void CheckPrime(int j) {
    int i = 1;          // Start checking from 1
    int count = 0;      // Counter to count number of factors

    while (i <= j) {
        if (j % i == 0) {       // If j is divisible by i
            count = count + 1;  // Increase the count
        }
        i++;                    // Move to next i
    }

    // After loop ends, check if the number has exactly 2 factors
    if (count == 2) {
        System.out.println(j + " is a prime number");
    } else {
        System.out.println(j + " is not a prime number");
    }
}

// Main method to check numbers from 150 to 300
public static void main(String[] args) {
    Numbers num = new Numbers(); // Create object of the class
    int j = 150;

    while (j <= 300) {
        num.CheckPrime(j); // Call the CheckPrime method
        j++;               // Move to the next number
    }
}
Enter fullscreen mode Exit fullscreen mode

}

OUTPUT Sample:

150 is not a prime number

151 is a prime number

152 is not a prime number

...

199 is a prime number

...

300 is not a prime number

Step-by-Step Explanation

public void CheckPrime(int j)
A method that takes one number j and checks if it is prime.

Uses a while loop to check how many numbers divide j completely (using j % i == 0).

If count == 2, it's a prime number.

Loop from 150 to 300

int j = 150;
while (j <= 300) {
num.CheckPrime(j);
j++;
}
This loop goes through each number from 150 to 300, calling the CheckPrime() method on each value of j.

Top comments (0)