function mersenne_factor(p){
  var limit, k, q
  limit = Math.sqrt(Math.pow(2,p) - 1)
  k = 1
  while ((2*k*p - 1) < limit){
    q = 2*k*p + 1
    if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){
      return q