Loading, please wait...

A to Z Full Forms and Acronyms

How to Print Prime Numbers in Java?

Aug 19, 2019 Java, 1684 Views
Program to display Prime Number between Interval

Let's create a program to display the prime no in a given range:

import java.util.*;
public class Primeno
{
    static boolean isprime(int n)
    {
        for(int i=2;i<=Math.sqrt(n);i++)
        {
            if(n%i==0)
            {
                return false;
            }
        }
        return true;
    }
	public static void main(String[] args) {
		int a;
		int b;
        System.out.println("Enter two intervals: ");
		Scanner sc=new Scanner(System.in);
		a=sc.nextInt();
		b=sc.nextInt();
		for(int i=a;i<b;i++)
		{
		    if(i<2)
		    {
		        System.out.println(i+" is not a prime no");
		    }
		    else if(isprime(i))
		    {
		        System.out.print(i+" ");
		    }
		}
	}
}

Output:

Enter two intervals:
5 50
5 7 9 11 13 17 19 23 29 31 37 41 47
A to Z Full Forms and Acronyms

Related Article