Toggle menu
9
204
47
18.7K
KenshiDB
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

This module displays the factorization of a given number. Numbers smaller than 2 or greater than 1,000,000,000 return "Error: <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 = {}

local function powerformat(divisor, power, productSymbol)
	if power < 1      then return ''
    elseif power == 1 then return divisor .. ' ' .. productSymbol .. ' '
    else return divisor .. '<sup>' .. power .. '</sup> ' .. productSymbol .. ' '
    end
end

local function format(numString, bold, big, serif)
    if bold then
    	numString = '<b>'..numString..'</b>'
    end

	local ret = (serif or big) and '<span ' or ''
	if serif then ret = ret .. 'class="texhtml" ' end
	if big   then ret = ret .. 'style="font-size:165%" ' end
	ret = ret .. ((serif or big) and '>' or '') .. numString .. ((serif or big) and '</span>' or '')

    return ret
end

function p.factor(frame)
	
    local number = tonumber(frame.args[1])
    if number == nil then
    	return '<strong class="error">Error: input not recognized as a number</strong>'
    end
    number = math.floor(number)
    if number < 2 or number > 1000000000 or number == math.huge then
        return '<strong class="error">Error: ' .. number .. ' out of range</strong>'
    end

    local result = ""
    local currentNumber = number
    local power = 0
    local divisor = 2
    local productSymbol = frame.args['product'] or '·'
    -- Attempt factoring by the value of the divisor
    -- divisor increments by 2, except first iteration (2 to 3)
    while divisor <= math.sqrt(currentNumber) do
        power = 0
        while currentNumber % divisor == 0 do
            currentNumber = currentNumber / divisor
            power = power + 1
        end

		-- Concat result and increment divisor
		-- when divisor is 2, go to 3. All other times, add 2
		result = result .. powerformat(divisor, power, productSymbol)
        divisor = divisor + (divisor == 2 and 1 or 2)
    end

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

    local primeLink = frame.args['prime'] and true
    if currentNumber == number and primeLink then
        return '[[prime number|prime]]'
    end

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

    local bold = frame.args['bold'] and true
    local big = frame.args['big'] and true
    local serif = frame.args['serif'] and true
    return format(result, bold, big, serif)
end

return p