/** * Copyright (c): Uwe Schmidt, FH Wedel * * You may study, modify and distribute this source code * FOR NON-COMMERCIAL PURPOSES ONLY. * This copyright message has to remain unchanged. * * Note that this document is provided 'as is', * WITHOUT WARRANTY of any kind either expressed or implied. */ /** * @author: Uwe Schmidt * * prime number test * all numbers are represented by the * java long datatype, but calls to * these functions are only meaningful * with arguments > 0 */ //-------------------- class Prime { /** * the test and start routine */ public static void main(String[] args) { System.out.println ( "prime number test\n" + "\n" + "test cases:\n" + "\n" + "isPrime( 1) == " + isPrime( 1) + "\n" + "isPrime( 2) == " + isPrime( 2) + "\n" + "isPrime( 11) == " + isPrime( 11) + "\n" + "isPrime( 91) == " + isPrime( 91) + "\n" + "isPrime(561) == " + isPrime(561) + "\n" + "\n" + "smallestDivisor( 11) == " + smallestDivisor( 11) + "\n" + "smallestDivisor( 91) == " + smallestDivisor( 91) + "\n" + "smallestDivisor(561) == " + smallestDivisor(561) + "\n" + "\n" + "isPrimeProduct( 1) == " + isPrimeProduct( 1) + "\n" + "isPrimeProduct( 2) == " + isPrimeProduct( 2) + "\n" + "isPrimeProduct( 11) == " + isPrimeProduct( 11) + "\n" + "isPrimeProduct( 91) == " + isPrimeProduct( 91) + "\n" + "isPrimeProduct(561) == " + isPrimeProduct(561) + "\n" ); try { isPrime(-1); } catch (IllegalArgumentException e) { System.out.println ( "isPrime(-1): exception: " + e.getMessage()); } } //-------------------- protected static long findDivisor(long n, long i) { return (i * i > n) ? n : (n % i) == 0 ? i : findDivisor(n, i+1); } //-------------------- public static long smallestDivisor(long n) { assert n > 0; return findDivisor(n,2); } //-------------------- public static boolean isPrime(long n) { assert n > 0; return n != 1 && smallestDivisor(n) == n; } //-------------------- public static boolean isPrimeProduct(long n) { assert n > 0; return isPrime(n / smallestDivisor(n)); } } //--------------------