 # @param {BigInteger} n
 # @return {Boolean} true if the check succeeds and false otherwise.
 #
+fta = new Avg()
 fermat2_test = (n) ->
-  tmr = new Timer()
+  fta.start()
   t = nbv(1)
   bl = n.bitLength()
   bl--
   for i in [bl..0]
-    t = t.square()
+    t = t.modPowInt(2,n)
+    #t = t.square()
 
     # .t in jsbn is equivalent to _mp_size in GNU bigint.  _mp_size
     # is the "number of limbs" in the bigint
-    if t.t > n.t
-      t = t.mod(n)
+    #if t.t > n.t
+    #  t = t.mod(n)
     if n.testBit(i)
       t = t.shiftLeft(1)
   if t.compareTo(n) > 0
     t = t.mod(n)
   ret = (t.compareTo(nbv(2)) is 0)
-  console.log "ran in #{tmr.stop()}"
+  fta.stop()
   ret
 
 #--------------

class Timer
  constructor : () -> @start = Date.now()
  stop : -> (Date.now() - @start)

#=================================================================


exports.miller_rabin = miller_rabin
exports.random_prime = random_prime

await random_prime 4096, 30, defer p
console.log p.toString()
console.log "avg -> #{fta.avg()}"
process.exit -1

