This is the syntax highlighted version of Prime.java.
/*************************************************************************
* Compilation: javac Primes.java
* Execution: java Primes N
*
* Determines whether or not N is prime.
*
* % java Prime 81
* false
*
* % java Prime 17
* true
*
* % java Prime 30864324691489
* false
*
* If N has a factor that it has one less than or equal to sqrt(N).
* Thus, for efficiency we stop checking for factors when we
* reach sqrt(N).
*
*************************************************************************/
public class Prime {
public static void main(String[] args) {
long N = Long.parseLong(args[0]);
boolean isPrime = true;
for (long i = 2; i*i <= N; i++) {
if (N % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime);
}
}
Last updated: Wed Feb 11 18:07:23 EST 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.