import java.util.Scanner; public class PrimeTest1 { /*******************************************************************************/ /** * This is a particularly mindless version of a prime-testing program that will * test whether an input integer 'n' is prime or not by trial dividing by all * integers less than or equal to the square root of the integer. * * There is nothing to commend this program to anyone except as an * example of a program that has a simple loop and a simple test. * Subsequent versions of this program will do things in a more classy way. * * Details (written here so as not to clutter up the code): * We import the Scanner class at the top and use it for console input. * * Mathematically, we know there must be a divisor lessequal the square root. * * We use the built in function Math.sqrt() to take the square root. * This also requires casting 'n' to a double for the sqrt method and * then casting the result back to an integer. * * In this program we end from inside the loop. This is bad form and in * the next version we will end more smoothly. * * @author Duncan Buell * 3 February 2008 **/ public static void main(String[] args) { int divisor,n,root; Scanner console = new Scanner(System.in); // The nextInt method of Scanner takes the next integer input from the console n = console.nextInt(); System.out.println("Test " + n + " for primality"); divisor = 2; root = (int) Math.sqrt((double) n); System.out.println("Test for divisors up to " + root); while(divisor <= root) { // print from inside the loop to make sure that the program is executing as expected System.out.println("Test " + divisor + " as a possible divisor "); if(0 == (n % divisor)) { System.out.println("The number " + n + " is divisible by " + divisor + " and thus is not prime"); System.out.println("Program terminating normally"); System.exit(0); } divisor = divisor + 1; } // while(divisor <= root) // If we run through all possible divisors and don't find one that divides, then the number must be prime. System.out.println("The number " + n + " is prime"); System.out.println("Program terminating normally"); } } // public class PrimeTest1