Find out the prime number in java

Posted By: Java Examples - 6:02 PM

Share

& Comment



 Prime number


We will be read how to get prime number between 1 to given number. First of all we have to define a class "primenum ". Java  util package has a input  in which  Scanner input=new Scanner(System.in)  is used for reading the input stream . As in this program we are going to insert certain instruction by creating  Scanner class.
Now applying in this program we use two 'for' loop. For loop will start from 1 to entered number. And another loop will start and divide it from 2 to less than those number. If number is divided by any number that means it is not prime otherwise prime number.

Source Code


import java.util.Scanner;
public class primenum {
int n;
public primenum()
{
Scanner input=new Scanner(System.in);
System.out.println("Enter the Number");
n=input.nextInt();
}                                                              
public void assignprime()
{
int i;
for (i=2;i<n;i++)
{
if(n%i==0)
{
System.out.println("This is not Prime number");
break;
}
}
if(i==n)
{
System.out.println("This is Prime number");
}
}
public static void main (String args[])
{
primenum prime=new primenum();
prime.assignprime();
}
}

Output



Download 





About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

0 comments :

Post a Comment

Thank you for vising Java90.blogspot.com

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .