function fannkuch(n) {
   var perm1 = [n]
   var i = 0
   var k = null
   var r = null
   var t = null
   var p0 = null
   var j = null
   var more = null
   for (i = 0; i < n; i++) perm1[i] = i
   var perm = [n]
   var count = [n]
   var f = 0
   var flips = 0
   var nperm = 0
   var checksum = 0

   r = n
   while (r > 0) {
      i = 0
      while (r != 1) { count[r-1] = r; r -= 1 }
      while (i < n) { perm[i] = perm1[i]; i += 1 }

      f = 0
      k = perm[0]
      while (k != 0) {
         i = 0
         while (2*i < k) {
            t = perm[i]; perm[i] = perm[k-i]; perm[k-i] = t
            i += 1
         }
         k = perm[0]
         f += 1
      }
      if (f > flips) flips = f
      if ((nperm & 0x1) == 0) checksum += f; else checksum -= f

      more = true
      while (more) {
         if (r == n) {
            log.console( checksum )
            return flips
         }
         p0 = perm1[0]
         i = 0
         while (i < r) {
            j = i + 1
            perm1[i] = perm1[j]
            i = j
         }
         perm1[r] = p0

         count[r] -= 1
         if (count[r] > 0) more = false; else r += 1
      }
      nperm += 1
   }
   return flips;
}

var n = arg[0] || 10

log.console(`Pfannkuchen(${n}) = ${fannkuch(n)}`)

$stop()