# Java program to find first N prime numbers

Learn to write program to find first prime numbers using Java 8 Stream API, where N is any given input number to the application.

## 1. Prime number algorithm

A prime number (P) is a number greater than 1 whose only factors are 1 and the number (P) itself. Generally, we can determine a number is prime or not in below steps:

1. 2 is only prime number which is also even number. So, if given number N is 2 the it is PRIME number.
2. If given number N is even number then it is NOT PRIME number.
3. Find out square root on N. Traverse all odd numbers up to the `sqrt(N)` and try to devide the N with current odd number. If remainder is 0 for any odd number then number is NOT PRIME.
4. Else – number is PRIME.
```static boolean isPrime(int number) {
if(number <= 2)
return number == 2;
else
return  (number % 2) != 0
&&
IntStream.rangeClosed(3, (int) Math.sqrt(number))
.filter(n -> n % 2 != 0)
.noneMatch(n -> (number % n == 0));
}
```

## 2. Program to find first N primes

Given program uses Java 8 stream apis to find first N prime numbers in series. In this program, user is asked an input where he chooses to input the number of primes he wants to generate.

E.g. if user enters 100 then program will generate first 100 prime numbers (starting with 2).

```package com.howtodoinjava.example;

import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main
{
public static void main(String[] args)
{
//Read input from console - optional
Scanner scan= new Scanner(System.in);
System. out.println("Enter a number : ");
int number = scan.nextInt();
scan.close();

List<Integer> primes = IntStream.range(2, Integer.MAX_VALUE)
.filter(n -> isPrime(n))
.limit(number)		//Limit the number of primes here
.boxed()
.collect(Collectors.toList());

System.out.println(primes);
}

static boolean isPrime(int number) {
if(number <= 2)
return number == 2;
else
return  (number % 2) != 0
&&
IntStream.rangeClosed(3, (int) Math.sqrt(number))
.filter(n -> n % 2 != 0)
.noneMatch(n -> (number % n == 0));
}
}
```

Program output.

```Enter a number :
10

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

============

Enter a number :
30

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]
```

Drop me your questions related to printing all first N prime numbers in Java.

Happy Learning !!

References: