Learn to write program for finding all the prime numbers from 1 and N, 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:

- 2 is only prime number which is also even number. So, if given number N is 2 the it is PRIME number.
- If given number N is even number then it is NOT PRIME number.
- Find out square root on N. Traverse all odd numbers up to the
`sqrt(N)`

and try to divide the N with current odd number. If remainder is 0 for any odd number then number is NOT PRIME. - 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. Java program to find prime numbers between 2 and N

In given below program, we have used `IntStream`

to iterate from 2 to 100 and find all prime numbers between them.

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.rangeClosed(2, number) .filter(n -> isPrime(n)) .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 : 100 [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]

It’s clear from output that program is able to **print all prime numbers between 2 to 100**.

Happy Learning !!

References: