1 回答
TA贡献1820条经验 获得超10个赞
将n所有主要因子的每个拆分分解并测试为 3 组
function split_number_into_factors_having_min_sum(n, factors)
assert(n > 0 and factors > 0)
local primes = {}
local degrees = {}
local terms = {}
local p = 2
local step = {4, 1, 2, 0, 2}
local m = 0
while n > 1 do
if p * p > n then
p = n
end
if n % p == 0 then
local d = 0
repeat
d = d + 1
n = n / p
until n % p ~= 0
m = m + 1
primes[m] = p
degrees[m] = d
terms[m] = {}
end
p = p + step[p % 6]
end
local parts = {}
for j = 1, factors do
parts[j] = 1
end
local best_sum = math.huge
local best_parts = {}
local process_next_prime
local function split_in_terms(sum, qty, k)
if qty < factors then
local max_val = parts[qty] == parts[qty + 1] and sum > terms[k][qty] and terms[k][qty] or sum
qty = qty + 1
local min_val = qty == factors and sum or 0
for val = min_val, max_val do
terms[k][qty] = val
split_in_terms(sum - val, qty, k)
end
else
local p = primes[k]
for j = 1, factors do
parts[j] = parts[j] * p^terms[k][j]
end
process_next_prime(k)
for j = 1, factors do
parts[j] = parts[j] / p^terms[k][j]
end
end
end
function process_next_prime(k)
if k < m then
split_in_terms(degrees[k + 1], 0, k + 1)
else
local sum = 0
for j = 1, factors do
sum = sum + parts[j]
end
if sum < best_sum then
best_sum = sum
for j = 1, factors do
best_parts[j] = parts[j]
end
end
end
end
process_next_prime(0)
table.sort(best_parts)
return best_parts
end
用法:
local t = split_number_into_factors_having_min_sum(100, 3)
print(unpack(t)) --> 4 5 5
添加回答
举报