Monday, September 14, 2015

Java program print prime numbers


This java program prints prime numbers, number of prime numbers required is asked from the user. Remember that smallest prime number is 2.

Java programming code


import java.util.*;
 
class PrimeNumbers
{
 public static void main(String args[])
 {
 int n, status = 1, num = 3;
 
 Scanner in = new Scanner(System.in);
 System.out.println("Enter the number of prime numbers you want");
 n = in.nextInt();
 
 if (n >= 1)
 {
 System.out.println("First "+n+" prime numbers are :-");
 System.out.println(2);
 }
 
 for ( int count = 2 ; count <=n ; )
 {
 for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
 {
 if ( num%j == 0 )
 {
 status = 0;
 break;
 }
 }
 if ( status != 0 )
 {
 System.out.println(num);
 count++;
 }
 status = 1;
 num++;
 } 
 }
}

Output of program:


We have used sqrt method of Math package which find square root of a number. To check if an integer(say n) is prime you can check if it is divisible by any integer from 2 to (n-1) or check from 2 to sqrt(n), first one is less efficient and will take more time.

Related Posts:

  • Java methods Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. In this tutorial we will… Read More
  • Using multiple classes in Java program Java program can contain more than one i.e. multiple classes. Following example Java program contain two classes: Computer and Laptop. Both classes h… Read More
  • 10 Major Differences Between C And JAVA Here are the major differences between C And JAVA. 1. JAVA is Object-Oriented while C is procedural. Different Paradigms, that is. Most differences… Read More
  • Java while loop Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. … Read More
  • Java static block program Java programming language offers a block known as static which is executed before main method executes. Below is the simplest example to understand f… Read More

0 Comments:

Post a Comment