Module:Utils: Difference between revisions

Fredg999 (talk | contribs)
Updated round to use string library, also now uses 6 significant digits by default
Fredg999 (talk | contribs)
Added is_prime and prime_factorization
Line 48: Line 48:
prec = p.eval_num_arg(prec, 6)
prec = p.eval_num_arg(prec, 6)
return string.format(string.format("%%.%dg", prec), x)
return string.format(string.format("%%.%dg", prec), x)
end
-- cached list of primes for is_prime
local primes = {}
-- returns true if integer n is prime; cannot be used with {{#invoke:}}
function p.is_prime(n)
  local cached = primes[n]
  if cached ~= nil then
    return cached
  end
  for i = 2, math.sqrt(n) do
    if n % i == 0 then
      primes[n] = false
      return false
    end
  end
  primes[n] = true
  return true
end
-- returns prime factorisation of integer n > 2 (with wiki markup for exponents)
function p.prime_factorization(frame)
local args = getArgs(frame)
return p._prime_factorization(args[1])
end
function p._prime_factorization(n)
  local factors, powers = {}, {}
  local new_number = n
  for i = 2, n do
    if p.is_prime(i) then
      if new_number % i == 0 then
        factors[#factors + 1] = i
        powers[#factors] = 0
      end
      while new_number % i == 0 do
        powers[#factors] = powers[#factors] + 1
        new_number = new_number / i
      end
      powers[#factors] = factors[#factors] .. "<sup>" .. powers[#factors] .. "</sup>"
    end
    if new_number == 1 then
      break
    end
  end
  return table.concat(powers, " × ")
end
end


return p
return p