Java for loop check if a number is a prime number

Question

We would like to know if a number is a prime number.

For example, for 23, it should display 'prime'. For 24 it should display "not prime".

You can use the following code structure to start

public class Main {
  public static void main(String args[]) {
    int num = 14;//your number
    boolean isPrime = false;

    // your code//  www .  ja va 2 s .c o m
    
    
    // end of checking
    
    if (isPrime) {
      System.out.println("Prime");
    } else {
      System.out.println("Not Prime");
    }
  }
}

Here is a simple program that tests for prime numbers.



// Test for primes.
public class Main {
  public static void main(String args[]) {
    int num = 14;
    boolean isPrime;
    if (num < 2) {
      isPrime = false;
    } else {
      isPrime = true;
    }
    for (int i = 2; i <= num / i; i++) {
      if ((num % i) == 0) {
        isPrime = false;
        break;
      }
    }

    if (isPrime) {
      System.out.println("Prime");
    } else {
      System.out.println("Not Prime");
    }
  }
}



PreviousNext

Related