gpt4 book ai didi

尽可能考虑几个因素的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:40:01 26 4
gpt4 key购买 nike

是否有已知算法将整数分解为尽可能少的因子(不一定是质数),其中每个因子都小于某个给定常数 N?

我不关心质因数大于 N 的数字。另外,我不处理大于几百万的数字,因式分解是处理初始化的一部分,所以我不是特别担心计算复杂度。

编辑:为了清楚起见。我已经有代码找到主要因素。我正在寻找一种方法,将这些因素组合成尽可能少的复合因素,同时保持每个因素小于 N。

最佳答案

您可以将问题分为两部分来解决:

  1. 使用 standard techniques 中的任何一个将您的数字因式分解为质数.对于几百万的数字,试分完全没问题。

  2. 对每个因素取对数,pack them into bins大小为 log N

现在,装箱是NP-hard但在实践中,可以使用简单的技术找到良好的近似解:首次拟合算法打包不超过最佳 bin 数量的 11/9(加一个 bin)。

这是 Python 中的一个实现:

from math import exp, log, sqrt
import operator

def factorize(n):
"""
Factorize n by trial division and yield the prime factors.

>>> list(factorize(24))
[2, 2, 2, 3]
>>> list(factorize(91))
[7, 13]
>>> list(factorize(999983))
[999983]
"""
for p in xrange(2, int(sqrt(n)) + 1):
while n % p == 0:
yield p
n //= p
if n == 1:
return
yield n

def product(s):
"""
Return the product of the items in the sequence `s`.

>>> from math import factorial
>>> product(xrange(1,10)) == factorial(9)
True
"""
return reduce(operator.mul, s, 1)

def pack(objects, bin_size, cost=sum):
"""
Pack the numbers in `objects` into a small number of bins of size
`bin_size` using the first-fit decreasing algorithm. The optional
argument `cost` is a function that computes the cost of a bin.

>>> pack([2, 5, 4, 7, 1, 3, 8], 10)
[[8, 2], [7, 3], [5, 4, 1]]
>>> len(pack([6,6,5,5,5,4,4,4,4,2,2,2,2,3,3,7,7,5,5,8,8,4,4,5], 10))
11
"""
bins = []
for o in sorted(objects, reverse=True):
if o > bin_size:
raise ValueError("Object {0} is bigger than bin {1}"
.format(o, bin_size))
for b in bins:
new_cost = cost([b[0], o])
if new_cost <= bin_size:
b[0] = new_cost
b[1].append(o)
break
else:
b = [o]
bins.append([cost(b), b])
return [b[1] for b in bins]

def small_factorization(n, m):
"""
Factorize `n` into a small number of factors, subject to the
constraint that each factor is less than or equal to `m`.

>>> small_factorization(2400, 40)
[25, 24, 4]
>>> small_factorization(2400, 50)
[50, 48]
"""
return [product(b) for b in pack(factorize(n), m, cost=product)]

关于尽可能考虑几个因素的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12425202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com