Home Java Javatutorial Prime Number in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Prime Number in Java

Advertisement
In this Java Tutorial, we will learn how to write a Java program to get the prime numbers from 1 to the given number.

Prime Number in Java

In this Java tutorial , you will learn how to write a Java program to get prime numbers between 1 to the desired number.

To start with, we have defined a class "PrimeNumber" in this example. Java I/O package has both input as well as output stream. The input stream is used to read the stream and to allocate the memory, while the output stream is used to write the bytes.

In this example of writing java program to get prime numbers, we will insert some instructions by creating buffer reader class. To proceed with, we will have to create a buffer for the string class, which can be used to instantiate a changeable object in order to store and process a string of character.

After that, we have used the ParseInt method to convert the parses into the string argument and define 'num' as an integer.

Now to execute the program, we have used 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 numbers. Moreover, if the number is divisible by any number, it means it is not prime otherwise prime number.

Advertisement

Here is the code of the java Program to get prime numbers:

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);
  }
  }
  }
}
Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 10, 2013

Ask Questions?    Discuss: Prime Number in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
tejaswini
October 27, 2013
palindrome

superb
DMCA.com