# Prime number in java: Algorithm and Programs

#### What is a prime number in Java?

A prime number in java is a number that is greater than 1 and divided by 1 or itself only. or we can say that a prime number can be divided by 1 or itself.

A number greater than 1 that is not prime is called a composite number.

for example:- 7 is a prime number because 7*1=7 or 1*7=7.

2=1,2 it is prime

3=1,2 it is prime

4=1,2,4 it is not prime

5=1,5 it is prime

6=1,2,3,6 it is not prime

#### Algorithm of prime number

simple steps of prime number:-

```START
Step 1 → Take integer variable num
Step 2 → Divide the variable num with (num-1 to 2)
Step 3 → If num is divisible by any value (num-1 to 2)  not prime
Step 4 → Else it is prime
STOP```

#### Prime Number in java using a for loop

``````public class Main {

public static void main(String[] args) {

int a = 11;
boolean flag = false;
for (int loop = 2; loop <= a / 2; ++i) {
// condition for nonprime number
if (a % loop == 0) {
flag = true;
break;
}
}

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

#### Output

`11 is a prime number`

#### Prime Number in java using a while loop

``````public class Main {

public static void main(String[] args) {

int a = 11, loop = 2;
boolean flag = false;
while (loop <= a / 2) {
// condition for nonprime number
if (a % loop == 0) {
flag = true;
break;
}

++loop;
}

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

#### Output

`11 is a prime number `

#### Prime Number in Java using Scanner

import java.util.Scanner;

import java.util.Scanner;

public class Prime {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.print(“Enter a number : “);

int num = s.nextInt();

if (isprime(num)) {

System.out.println(“it is a prime number”);

}

else {

System.out.println(” it is not a prime number”);

}

}

public static boolean isprime(int num) {

if (num <= 1) {

return false;

}

for (int loop = 2; loop < Math.sqrt(num); loop++) {

if (num % loop == 0) {

return false;

}

}

return true;

}

}

#### Output

```Enter the number : 3
it is a prime number```

For Fibonacci series Algorithm and programs click here