// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
public class SlowSqrt {
    private final static int N = 10000000;
    public final static double PREC = 0.000001;
    static {
        System.loadLibrary("sqrtlib");
    }
    public static double sqrtalgorithm(double x) {
        double res = 0.5*x;
        while(Math.abs(1 - x/(res*res)) > PREC) {
            res = 0.5*(res + x/res);
        }
        return res;
    }
    public native static double sqrtnative(double x);
    public static void main(String[] args) {
        double x;
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            x = Math.sqrt(i);
            if(x>i+1) throw new RuntimeException("Oops");
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Math.sqrt: " + (t2-t1));
        long t3 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            x = SlowSqrt.sqrtalgorithm(i);
            if(x>i+1) throw new RuntimeException("Oops");
        }
        long t4 = System.currentTimeMillis();
        System.out.println("SlowSqrt.sqrtalgorithm: " + (t4-t3));
        long t5 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            x = SlowSqrt.sqrtnative(i);
            if(x>i+1) throw new RuntimeException("Oops");
        }
        long t6 = System.currentTimeMillis();
        System.out.println("SlowSqrt.sqrtnative: " + (t6-t5));
    }
}
