Prime number program in JAVA

Let us make another basic program in JAVA.i.e finding the prime numbers in the given list.We know that a number is called as prime number if it is divisible by one and itself only.Therefore to check whether a number is prime or not,we need to divide the number and depending on remainder we decide it.If the remainder is zero then it is prime number if not it is composite number.
Now,we shall create a program such that we shall ask an input which we use it as an limit to find to the prime number from 1 to the given input.

class finding
{
   int flag,n;
   finding()
     {
       System.out.print("Enter range to find the prime numbers:");
       Scanner in=new Scanner(System.in);
       n=in.nextInt();
       for(int i=2;i<n;i++)
        {
            flag=0;
           for(int j=2;j<i;j++)
             {
                 if(i%j ==0)
                    flag++;
             }
           if(flag==0)
            System.out.println(&quot;one of the prime number is:&quot; + i);
        }
    }
}
class prime
{
   public static void main(String a[])    
      {
           finding ob=new finding();
      }
}

Explanation:Here class prime contains the main function.In main function we declared an object of the class finding and a constructor is invoked implicitly.There we asked to enter the limit of the program.In the first for loop we are considering a number and in the second for loop we are dividing the number with all the number which are less than the considered number.If the number is divisible is by any number other than 1 and itself then the number is not a prime number.

The Output of the program is:
prime
You can download the program.

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s