Advertisement
JeffGrigg

Untitled

Dec 22nd, 2017
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.13 KB | None | 0 0
  1. public class PrimeExample {
  2.  
  3.     public static void main(String args[]) {
  4.  
  5.         final int numberToBeChecked = 3;//it is the number to be checked
  6.  
  7.         boolean isPrime = isPrime(numberToBeChecked);
  8.  
  9.         if (isPrime) {
  10.             System.out.println(numberToBeChecked + " is prime number");
  11.         } else {
  12.             System.out.println(numberToBeChecked + " is not prime number");
  13.         }
  14.     }
  15.  
  16.     protected static boolean isPrime(final int numberToBeChecked) {
  17.         boolean isPrime = false;
  18.         if (numberToBeChecked == 0 || numberToBeChecked == 1) {
  19.             isPrime = false;
  20.         } else {
  21.             boolean foundFactor = false;
  22.             int largestDivisorToTry = numberToBeChecked / 2;
  23.             for (int divisor = 2; divisor <= largestDivisorToTry; divisor++) {
  24.                 if (numberToBeChecked % divisor == 0) {
  25.                     isPrime = false;
  26.                     foundFactor = true;
  27.                     break;
  28.                 }
  29.             }
  30.             if (!foundFactor) {
  31.                 isPrime = true;
  32.             }
  33.         }//end of else
  34.         return isPrime;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement