Java tutorial
//package com.java2s; //License from project: Open Source License public class Main { public static boolean test(int i) { if (i < 0) { throw new ArithmeticException("Cannot determine if a negative value is prime"); } else if (i == 0) { throw new ArithmeticException("Cannot determine if zero is prime"); } else if (i == 1) { throw new ArithmeticException("Cannot determine if one is prime"); } else if (i == 2) { return true; } else { return unprotectedTest(i); } } public static boolean test(long l) { if (l < 0) { throw new ArithmeticException("Cannot determine if a negative value is prime"); } else if (l == 0) { throw new ArithmeticException("Cannot determine if zero is prime"); } else if (l == 1) { throw new ArithmeticException("Cannot determine if one is prime"); } else if (l == 2) { return true; } else { return unprotectedTest(l); } } public static int[] test(int[] intArray) { int[] returnArrayTemp = new int[intArray.length]; for (int n = 0, m = intArray.length; n < m; n++) { int i = intArray[n]; if (i < 0) { throw new ArithmeticException("Cannot determine if a negative value is prime"); } else if (i == 0) { throw new ArithmeticException("Cannot determine if zero is prime"); } else if (i == 1) { throw new ArithmeticException("Cannot determine if one is prime"); } else if (i == 2) { returnArrayTemp[n] = i; } else { if (unprotectedTest(i) == true) { returnArrayTemp[n] = i; } } } int[] returnArray = arrayCopy(returnArrayTemp); return returnArray; } private static boolean unprotectedTest(int i) { for (int n = 2, max = (int) Math.ceil(Math.sqrt(i)); n <= max; n++) { if (i % n == 0) { return false; } } return true; } private static boolean unprotectedTest(long l) { for (int n = 2, max = (int) Math.ceil(Math.sqrt(l)); n <= max; n++) { if (l % n == 0) { return false; } } return true; } private static int[] arrayCopy(int[] x) { int z = 0; int[] l = new int[x.length + 1]; for (int i = 0; i < x.length; i++) { int y = x[i]; if (y != 0) { l[z] = y; z++; } } int[] n = new int[z]; System.arraycopy(l, 0, n, 0, z); return n; } }