Friday, November 20, 2015

Java Program to Check if an Integer is Prime or Not

A number is called a prime number if its only divisible by 1 or itself, which means prime number doesn't have any positive divisor other than itself.

import java.util.Scanner;

/**
 * Simple Java program to print prime numbers from 1 to 100 or any number.
 * A prime number is a number which is greater than 1 and divisible
 * by either 1 or itself.
 */

public class PrimeNumberExample {

    public static void main(String args[]) {
      
     //get input till which prime number to be printed
      System.out.println("Enter the number till which prime number to be printed: ");
      int limit = new Scanner(System.in).nextInt();
    
      //printing primer numbers till the limit ( 1 to 100)
      System.out.println("Printing prime number from 1 to " + limit);
      for(int number = 2; number<=limit; number++){
          //print prime numbers only
          if(isPrime(number)){
              System.out.println(number);
          }
      }
    }

    /*
     * Prime number is not divisible by any number other than 1 and itself
     * @return true if number is prime
     */

    public static boolean isPrime(int number){
        for(int i=2; i<number; i++){
           if(number%i == 0){
               return false; //number is divisible so its not prime
           }
        }
        return true; //number is prime now
    }

/*With some more efficient coding - checking the number is prime or not
When numbers are large checking every integer (up to n to find out that a number is prime) to just checking half of the integers up to the square root (the odd ones, really)
*/
    public static boolean isPrime(int n) {
    //check if n is a multiple of 2
    if (n%2==0) return false;
    //if not, then just check the odds
    for(int i=3;i*i<=n;i+=2) {
        if(n%i==0)
            return false//number is divisible so its not prime
    }
      return true//number is prime now
   }
}

Output:
Enter the number till which prime number to be printed:
20
Printing prime number from 1 to 20
2
3
5
7
11
13
17
19


No comments:

Post a Comment