Write a Java Program to Check Whether a Number is Prime or Not

Java Program to Check Whether a Number is Prime or Not

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Check Whether a Number is Prime or Not
Java Program to Check Whether a Number is Prime or Not

Write a Java Program to Check Whether a Number is Prime or Not

PROGRAM: Java Program to Check Whether a Number is Prime or Not

/* Java Program to Check Whether a Number is Prime or Not */

1: Program to Check Prime Number using a for loop

public class Main {

public static void main(String[] args) {

int num = 29;
boolean flag = false;

// 0 and 1 are not prime numbers
if (num == 0 || num == 1) {
flag = true;
}

for (int i = 2; i <= num / 2; ++i) {

// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}

if (!flag)
System.out.println(num + ” is a prime number.”);
else
System.out.println(num + ” is not a prime number.”);
}
}

2: Program to Check Prime Number using a while loop

public class Main {

public static void main(String[] args) {

int num = 33, i = 2;
boolean flag = false;

// 0 and 1 are not prime numbers
if (num == 0 || num == 1) {
flag = true;
}

while (i <= num / 2) {

// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}

++i;
}

if (!flag)
System.out.println(num + ” is a prime number.”);
else
System.out.println(num + ” is not a prime number.”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *