Jump to content

Module:Factorization

Frá Wikipedia, hin frælsa alfrøðin

This template displays the factorization of a given number. Numbers smaller than 2 or greater than 1,000,000,000 return "number out of range". Fractional numbers are rounded down.

Parameters
  • The first unnamed parameter is the number
  • Product - the symbol to be used to indicate times. Defaults to ·
  • Bold - set to any value to make it bold
  • Serif - set to any value to make it serif
  • Big - set to any value to make it big
  • Prime - set to any value to have prime numbers return an unformatted link to prime instead of the number

local p = {}

function p.factor(frame)
    number = tonumber(frame.args[1])
    productSymbol = frame.args['product'] or '·'
    bold = frame.args['bold'] and true
    big = frame.args['big'] and true
    serif = frame.args['serif'] and true
    primeLink = frame.args['prime'] and true

    number = math.floor(number)
    if number < 2 or number > 1000000000 then
        return '<strong class="error">number out of range</strong>'
    end

    result = ""
    currentNumber = number
    power = 0
    
    --First take care of 2, the only even prime number.
    if currentNumber % 2 == 0 then
        result = '2'
        currentNumber = currentNumber / 2
        power = 1
    end

    while currentNumber % 2 == 0 do
        currentNumber = currentNumber / 2
        power = power + 1
    end

    if power > 1 then
        result = result..'<sup>'..power..'</sup>'..productSymbol..' '
    elseif power == 1 then
        result = result..' '..productSymbol..' '
    end

    --Now do all odd numbers.
    prime = 3

    while prime <= math.sqrt(currentNumber) do

        power = 0

        if currentNumber % prime == 0 then
            result = result..prime
            currentNumber = currentNumber / prime
            power = 1
        end

        while currentNumber % prime == 0 do
            currentNumber = currentNumber / prime
            power = power + 1
        end

        if power > 1 then
            result = result..'<sup>'..power..'</sup>'..productSymbol..' '
        elseif power == 1 then
            result = result..' '..productSymbol..' '
        end

        prime = prime + 2
    end

    if currentNumber ~= 1 then
        result = result..currentNumber..' '..productSymbol..' '
    end

    if currentNumber == number and primeLink then
        return '[['..'prime'..']]'
    end

    result = string.sub(result,1,-4)

    return format(result)
end

function format(num)
    if bold then
        num = '<b>'..num..'</b>'
    end

    if serif then
        if big then
            num = '<span class="texhtml" style="font-size:165%">'..num..'</span>'
        else
            num = '<span class="texhtml">'..num..'</span>'
        end
    elseif big then
        num = '<span style="font-size:165%">'..num..'</span>'
    end

    return num
end

return p