tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Articles > Java > Coding Examples > Prime Number

Prime Number 

Verify whether a given number is Prime number.

File Name  :  
com/bethecoder/tutorials/coding/examples/PrimeNumberTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.coding.examples;

public class PrimeNumberTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    for (int i = ; i < 20 ; i ++) {
      if(isPrimeNumber(i)) {
        System.out.println(i + " is a prime number");
      else {
        System.out.println(i + " is not a prime number");
      }
    }
  }

  private static boolean isPrimeNumber(int number) {
    boolean prime = true;
    number = Math.abs(number);

    if (number < 2) {
      prime = false;
    else {
      for (int i = ; i <= number/; i ++) {
        if (number % i == 0) {
          prime = false;
          break;
        }
      }
    }
    return prime;
  }

}
   

It gives the following output,
0 is not a prime number
1 is not a prime number
2 is a prime number
3 is a prime number
4 is not a prime number
5 is a prime number
6 is not a prime number
7 is a prime number
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number
12 is not a prime number
13 is a prime number
14 is not a prime number
15 is not a prime number
16 is not a prime number
17 is a prime number
18 is not a prime number
19 is a prime number


                    Print

   



Books Recommendation

 
 
bl  br