Java - Print Prime Numbers from 2 to N using Java Program.


IncludeHelp 07 August 2016

Prime Number Code in Java – The numbers which are divisibly by 1 and itself are prime numbers, in this example we are going to explain you how to check and prime numbers within a range.

In this code snippet, we will learn how to print prime numbers from 2 to N using java program, we will read a maximum number (n) and run loop from 2 to N, using a method isPrime() we will check whether number is prime or not, if it is primer we will print the number.

isPrime() is not a standard or library method we design method isPrime() that will return either true or false, if number is prime it will return true else it will return false.

To check prime number condition - we will run loop in isPrime() method from 2 to Number/2 - we should know that number cannot be divide more than half of itself. In this loop condition if number divides by any of the number between 2 to (Number/2)-1, number will not be prime.

Java Code Snippet - Print Prime Numbers from 2 to N using Java Program

//Java - Print Prime Numbers from 1 to N using Java Program.

import java.util.*;

public class PrintPrimeNumbers
{
	 //function to check number is prime or not
	  public static boolean isPrime(int number){
		  int i;
		  boolean flgPrime=true;
		  for(i=2; i<number/2; i++){
			  if(number%i==0){
				  flgPrime=false;
				  break;
			  }
		  }
		  return flgPrime;
	  }
	  public static void main(String args[]){
		  int loop,n;
		  
		  System.out.print("Enter value of n: ");
		  Scanner SC=new Scanner(System.in);
		  n=SC.nextInt();
		  
		  //run loop from 1 to n
		  for(loop=2; loop<n; ++loop){
			  if(isPrime(loop)){
				  System.out.println(loop);
			  }
		  }
		  SC.close();
	  }
}
    

    Enter value of n: 50
    2
    3
    4
    5
    7
    11
    13
    17
    19
    23
    29
    31
    37
    41
    43
    47



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.