Powered by Blogger.

Prime Number Logic

>> Sunday, December 11, 2011

The Prime Number program logic is simple but some times we can't catch immediately. In many interviews candidates will discuss each other about this logic. Here given as simply to understand the main logic.

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.

In this first for look the values repeat up to the given number 'num'. After it check the prime number logic.
The program given below.

package com.javabynataraj;
import java.io.*;

class PrimeNumber {
      public static void main(String[] args) throws Exception{
      int i;
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Enter number:");
          int num = Integer.parseInt(bf.readLine());
          System.out.println("Prime number: ");
            for (i=1; i < num; i++ ){
               int j;
               for (j=2; j<i; j++){
                 int n = i%j;
                  if (n==0){
                     break;
                  }
               }
               if(i == j){
                 System.out.print("  "+i);
               }
          }
       }
   }

You may get doubt on this how to compile a packaged program in command Prompt.We can compile by using javac -d . PrimeNumber.java in command prompt. Run the program by the command java com.javabynataraj.PrimeNumber . You have to give entire package name with dot(.) operator upto Program name.The output is given below for the above program.

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.