// Arup Guha
// 1/16/07
// An adaptation of prime.java that utilizes two static methods.

import java.io.*;

public class prime3 {

  final static double epsilon = 0.0001;

  public static void main(String[] args) {

    // Keeps track of if the first value has been printed.
    boolean firstval = true; 

    // Print header.
    System.out.print("The prime numbers in between 2 and 100 are ");
 
    // Loop through all the values in the range.
    for (int tryval=2; tryval<=100; tryval++) {

      // We only print something if the number is prime.
      if (prime3.isPrime(tryval)) {

        // If it's the first number, don't precede it with a comma.
        if (firstval) {
          System.out.print(tryval);
          firstval = false;
        }

        // Otherwise, print a comma and then the value.
        else
          System.out.print(", "+tryval);
      }

    } //  end for tryval
    
    // Finish the sentence!
    System.out.println(".");

  } // end main

  public static boolean isPrime(int n) {

    // If we get a negative number, check it's absolute value for 
    // primality instead.
    n = Math.abs(n);

    boolean prime = true;

    // Try dividing the number we are trying by all possibilities.
    // The +1 is to account for a possible rounding error.
    for (int trydiv=2; trydiv <= prime3.mysqrt(n) + epsilon; trydiv++) {

      // If it divides evenly, the number isn't prime.
      if (n%trydiv == 0) {
        prime = false;
        break;
      }
    }
    
    // Returns whether or not n is prime.
    return prime;
  }

  // Returns the square root of x, to within 0.0001, or epsilon.
  public static double mysqrt(double x) {

    // Only try finding the square root of positive values.
    if (x > 0) {

      double guess = 1; // An initial guess.

      // Refine the guess until it's pretty close.
      while (Math.abs(x - guess*guess) > epsilon)
        guess = (guess + x/guess)/2;

      // Return this guess.
      return guess;
    }

    return -1; // Our error value.
  }

} // end class
