/********************************************************************** * Matt Kretchmar * March 21, 2003 * PrimeTest * This program will test the user's input integer to see if it * is a prime number or not. **********************************************************************/ import java.util.Scanner; class PrimeTest { /******************************************************************** * main ********************************************************************/ public static void main ( String [] args ) { int n, x, y; Scanner keyboard = new Scanner(System.in); System.out.println("Enter x: "); x = keyboard.nextInt(); System.out.println("Is x prime? " + isPrime(x) ); } /******************************************************************** * evenlyGoesInto * This method returns true if y divides x evenly (with no remainder) * or returns false otherwise. ********************************************************************/ public static boolean evenlyGoesInto ( int x, int y ) { return ( x%y == 0 ); } /******************************************************************** * isPrime * This method returns true if x is prime, false otherwise. It works * by testing all numbers 2, 3, ... up through sqrt(x) to see if any * of them are factors (divide evenly) of x. If no factors are found, * then x is a prime number. ********************************************************************/ public static boolean isPrime ( int x ) { for ( int i = 2; i <= Math.sqrt(x); i++ ) { if (evenlyGoesInto(x,i)) return false; } return true; } }