import java.util.Scanner; public class PrimeTest2 { /*******************************************************************************/ /** * This is a somewhat improved program over version 1. Note that the flow of * control no longer ends the program in the middle. It is usually considered * bad form to end a program in the middle or in more than one place, since * that makes it harder to figure out how the flow of control works. * * The big difference in this program is that we use a 'divisorFound' variable. * If we come upon a divisor, we print the message and then set the 'divisorFound' * variable, which is tested at the beginning of the next iteration of the loop. * Since there's essentially nothing done beyond the test and to the end of the loop * except to increment the trial divisor by 1, we lose nothing by waiting to break * out of the loop until next we test the 'divisorFound' variable. * * Since in the previous program we exited the program upon finding a factor, * and in this one we always finish the loop, we have to test and print either * 'prime' or 'not prime' after we finish the loop. * * @author Duncan Buell * 3 February 2008 **/ public static void main(String[] args) { boolean divisorFound; int divisor,n,root; Scanner console = new Scanner(System.in); n = console.nextInt(); System.out.println("Test " + n + " for primality"); divisorFound = false; divisor = 2; root = (int) Math.sqrt((double) n); System.out.println("Test for divisors up to " + root); while( (divisor <= root) && (!divisorFound) ) { 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"); divisorFound = true; } divisor = divisor + 1; } // while( (divisor <= root) && (!divisorFound) ) if(divisorFound) { System.out.println("The number " + n + " is not prime"); } else { System.out.println("The number " + n + " is prime"); } System.out.println("Program terminating normally"); } } // public class PrimeTest2