Factoring numbers to roughly equal factors

I would like to decompose a number into a set of numbers as close as possible to each other in size, whose product is the starting number. The inputs are the number nwe want to determine and the number of mdesired factors.

For two factors ( m==2), it’s enough to find the largest coefficient less than the square root, so I can do something like this

def get_factors(n):
  i = int(n**0.5 + 0.5)
  while n % i != 0:
    i -= 1
  return i, n/i

So calling this using 120will result in 10,12.

I understand that there is some ambiguity about what it means that the numbers will be "close to each other in size." I do not mind if this is interpreted as minimizing Σ(x_i - x_avg)or Σ(x_i - x_avg)^2or something else in general along these lines.

In case m==3I would expect to 336create 6,7,8and 729to create 9,9,9.

Ideally, I would like to get a solution for the general m, but if someone has an idea even for m==3, it will be very appreciated. I welcome general heuristics.

EDIT: I would rather minimize the sum of the factors. Still interested in the above, but if someone has an idea for a way to determine the optimal value m, so that the sum of the factors is minimal, that would be great!

+4
source share
3 answers

( m ), . , , 4 , , , .

, , , , 4104, , 8 , [3, 9, 19], [6, 6, 6, 19]. DP . DP - , , , DP . - . , .

n = int(raw_input())
left = int(raw_input())


memo = {}
def dp(n, left): # returns tuple (cost, [factors])
    if (n, left) in memo: return memo[(n, left)]

    if left == 1:
        return (n, [n])

    i = 2
    best = n
    bestTuple = [n]
    while i * i <= n:
        if n % i == 0:
            rem = dp(n / i, left - 1)
            if rem[0] + i < best:
                best = rem[0] + i
                bestTuple = [i] + rem[1]
        i += 1

    memo[(n, left)] = (best, bestTuple)
    return memo[(n, left)]


print dp(n, left)[1]

[In] 4104
[In] 4 
[Out] [6, 6, 6, 19]
+1

, m = 3 n:

  • n , n, f1
  • n f1, g
  • " " g, m = 2.

336 , , 336, 6 ( ). 336 6 56 ( , !) 56 , 7 8.

, . m > 3, .

, , :

factors=[]
n=336
m=3

def getFactors(howMany, value):
  if howMany < 2:
    return value

  root=getRoot(howMany, value) # get the root of value, eg square root, cube, etc.
  factor=getLargestFactor(value, root) # get the largest factor of value smaller than root
  otherFactors=getFactors(howMany-1, value / factor)
  otherFactors.insert(factor)
  return otherFactors
print getFactors(n, m)

, , .

0

: m th, . .

def get_factors(n, m):
    factors = []
    factor = int(n**(1.0/m) + .1) # fudged to deal with precision problem with float roots
    while n % factor != 0:
        factor = factor - 1
    factors.append(factor)
    if m > 1:
        factors = factors + get_factors(n / factor, m - 1)
    return factors

print get_factors(729, 3)
0

All Articles