# Prime Number Program in Java

Last Updated : 06 Mar, 2024

A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example 2, 3, 5, 7, 11,….. are prime numbers.

In this article, we will learn how to write a prime number program in Java, when the input given is a Positive number.

## Methods to Write Prime Number Program in Java

For checking a prime number in Java there is no formulae available but there are a few methods available to check if a number is Prime or not. There are a few methods to check if a number is prime or not as mentioned below:

### 1. Simple Program to Check Prime in Java

A simple solution is to iterate through all numbers from 2 to n – 1 and for every number check if it divides n. If we find any number that divides, we return false.

Below is the Java program to implement the above approach:

## Java

 `// Java Program to demonstrate` `// Brute Force Method` `// to check if a number is prime` `class` `GFG {` `    ``static` `boolean` `isPrime(``int` `n)` `    ``{` `        ``// Corner case` `        ``if` `(n <= ``1``)` `            ``return` `false``;`   `        ``// Check from 2 to n-1` `        ``for` `(``int` `i = ``2``; i < n; i++)` `            ``if` `(n % i == ``0``)` `                ``return` `false``;`   `        ``return` `true``;` `    ``}`   `    ``// Driver Program` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``if` `(isPrime(``11``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `        ``if` `(isPrime(``15``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `    ``}` `}`

Output

``` true
false

```

#### The complexity of the above method

Time complexity:  O(n)

Space complexity: O(1)

### 2. Improved Method in Java to Check Prime

In this method, the check is done from 2 to n/2 as a number is not divisible by more than half its value.

Below is a Java program to implement the approach:

## Java

 `// JAVA program to demonstrate` `// Improved method` `// to check if a number is prime` `import` `java.util.Scanner;`   `// Driver Class` `class` `GFG {` `    ``static` `boolean` `isPrime(``int` `n)` `    ``{` `        ``// Corner case` `        ``if` `(n <= ``1``)` `            ``return` `false``;`   `        ``// Check from 2 to n/2` `        ``for` `(``int` `i = ``2``; i <= n / ``2``; i++)` `            ``if` `(n % i == ``0``)` `                ``return` `false``;`   `        ``return` `true``;` `    ``}`   `    ``// Driver Program` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``if` `(isPrime(``11``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `        ``if` `(isPrime(``15``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `    ``}` `}`

Output

``` true
false

```

#### Complexity of the above method

Time complexity: O(N)

Space complexity: O(1)

### 3. Optimized Java Code for Prime Number

Instead of checking till n, we can check till âˆšn because a larger factor of n must be a multiple of a smaller factor that has been already checked.

Below is the Java program to implement the above approach:

## java

 `// Java Program to demonstrate` `// Optimized method` `// to check if a number is prime` `import` `java.util.Scanner;`   `class` `GFG {` `    ``static` `boolean` `isPrime(``int` `n)` `    ``{` `        ``// Corner case` `        ``if` `(n <= ``1``)` `            ``return` `false``;`   `        ``// Check from 2 to sqrt(n)` `        ``for` `(``int` `i = ``2``; i <= Math.sqrt(n); i++)` `            ``if` `(n % i == ``0``)` `                ``return` `false``;`   `        ``return` `true``;` `    ``}`   `    ``// Driver Program` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``if` `(isPrime(``11``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `        ``if` `(isPrime(``15``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `    ``}` `}`

Output

``` true
false

```

#### Complexity of the above method

Time complexity: O(âˆšn)

Space complexity: O(1)

### 4. Most Optimized Method

The algorithm can be improved further by observing that all primes are of the form 6k Â± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4.

Note:  2 divides (6k + 0), (6k + 2), (6k + 4)

3 divides (6k + 3)

So, a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k Â± 1 â‰¤ âˆšn. This approach is 3 times faster than testing all numbers up to âˆšn.

Below is the Java program to implement the above approach:

## java

 `// JAVA program to demonstrate` `// Optimized method based` `// to check if a number is prime` `import` `java.util.Scanner;`   `class` `GFG {` `    ``static` `boolean` `isPrime(``int` `n)` `    ``{` `        ``// Corner case` `        ``if` `(n <= ``1``)` `            ``return` `false``;`   `        ``if` `(n == ``2` `|| n == ``3``)` `            ``return` `true``;`   `        ``if` `(n % ``2` `== ``0` `|| n % ``3` `== ``0``)` `            ``return` `false``;`   `        ``for` `(``int` `i = ``5``; i <= Math.sqrt(n); i = i + ``6``)` `            ``if` `(n % i == ``0` `|| n % (i + ``2``) == ``0``)` `                ``return` `false``;`   `        ``return` `true``;` `    ``}`   `    ``// Driver Program` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``if` `(isPrime(``11``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `        ``if` `(isPrime(``15``))` `            ``System.out.println(``" true"``);` `        ``else` `            ``System.out.println(``" false"``);` `    ``}` `}`

Output

``` true
false

```

#### Complexity of the above method

Time complexity: O(âˆšn)

Space complexity: O(1)

To know more, please refer to the complete article – Prime Numbers

Previous
Next