Monday, 12 September 2011

Prime Number in Java

This Java programming tutorial, we will be read how to get prime number between 1 to given number. First of all we have to define a class "PrimeNumber". Java I/O package has a input stream and a output stream in which input stream is used for reading the stream and memory allocating and the output stream used for writing bytes. As in this program we are going to insert certain instruction by creating buffer reader class. Here we have to create a buffer for the string class that can be used to instantiate a changeable object for storing and processing a string of character. Now use the ParseInt method for converting the parses the string argument and define 'num' as an integer.
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.
Here is the code of the Program
import java.io.*;

class PrimeNumber {
  public static void main(String[] argsthrows 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);
  }
  }
  }
}
 Download this Example.

No comments: