/*
* prime1 is a program to test for prime numbers
*/

class prime1 {
public static void main(String[] args) {
// Define the variables that will be used
int n=2; /*number to test*/
int i; /*divisor*/
boolean prime; /*is the number prime true or false?*/

// Test the arguments
if (args.length > 0) {
try {
n= Integer.parseInt(args[0]); /*Converts string from text to number*/
} catch (NumberFormatException e) {
System.err.println("You Must Enter a Natural Number");
System.exit(1);
}
}

if (n<2) {
System.err.println("You Must Enter a Natural Number > 2");
System.exit(1);
}

//Test for prime

prime=true;
for (i=2; i*i<=n; i++) { /*add 1 to divisor until greater than square root of number to test*/
if(n%i==+0) { /*if remainder=0, then its evenly divisible, and not prime*/
prime=false; /*set prime to false*/
System.out.println(n+ " is divisible by "+i); /*print divisor*/
}
}

System.out.println("The number "+n); /*print the number that was tested*/
if(prime) {
System.out.println(" is a prime"); /*if number is prime, display this*/
} else {
System.out.println(" is not a prime"); /*if the number is not prime, display this*/
}

}
}

Back to Programs.

Take Me Home!