Display Prime Numbers in Java

This post shows how you can generate and display prime numbers in Java in the given range.

A number is a prime number if can be divided either by 1 or by the number itself. So every number with in the given range has to be divided starting from 2 till number/2 in the loop. You only need to run your loop from 2 to N/2 (where N is the passed number), reason being no number is completely divisible by a number more than its half.

Java code to display prime numbers within the given range

import java.util.Scanner;

public class DisplayPrime {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter start number for displaying prime numbers  - ");
		int start = sc.nextInt();
		// Since 1 and 0 are not considered prime
		if(start == 0 || start == 1){
			start = 2;
		}
		System.out.println("Enter end number for displaying prime numbers  - ");
		int end = sc.nextInt();
		for(int i = start; i <= end; i++){
			if(isPrimeNumebr(i)){
				System.out.print(i + " ");
			}
		}
	}
	
	private static boolean isPrimeNumebr(int num){
		boolean flag = true;
		for(int i = 2; i < num/2; i++){
			// No remainder means completely divides  
			if(num % i == 0){
				flag = false;
				break;
			}
		}
		return flag;
	}
}

Output

Enter start number for displaying prime numbers  - 
1
Enter end number for displaying prime numbers  - 
20
2 3 4 5 7 11 13 17 19 

Enter start number for displaying prime numbers  - 
20
Enter end number for displaying prime numbers  - 
100
23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

Related Posts

That’s all for the topic Display Prime Numbers in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.