如何分解两个整数以进行网格创建

时间:2010-08-25 20:45:19

标签: algorithm

给定整数N我想找到满足A×B≥N的两个整数A和B,条件如下:

  1. A×B和N之间的差异尽可能低。
  2. A和B之间的差异尽可能低(接近正方形)。
  3. 示例:23。可能的解决方案3×8,6×4,5×5。6×4是最好的,因为它在网格中只留下一个空白空间,并且“小于”矩形比3×8。

    另一个例子:21。解决方案3×7和4×6。3×7是理想的解决方案。

    蛮力解决方案很容易。我想看看是否有可能找到一个聪明的解决方案。

3 个答案:

答案 0 :(得分:3)

易。

在伪代码中

a = b = floor(sqrt(N))

if (a * b >= N) return (a, b)

a += 1
if (a * b >= N) return (a, b)

return (a, b+1)

并且它将始终终止,ab之间的距离最多只有1。

如果你放松第二个约束会更难,但这是另一个问题。

编辑:因为看起来第一个条件更重要,你必须解决这个问题 有点不同。你必须指定一些方法来衡量 badness 不够正方形=第二个条件,因为即使素数也可以被分解为1*number,我们满足第一个条件。假设我们有一个坏函数(比如说a >= b && a <= 2 * b),然后分解N并尝试不同的组合来找到最好的一个。如果没有足够的好处,请尝试N+1,依此类推。

Edit2:在思考了一下之后,我用Python解决了这个问题:

from math import sqrt

def isok(a, b):
  """accept difference of five - 2nd rule"""
  return a <= b + 5

def improve(a, b, N):
  """improve result:
    if a == b:
       (a+1)*(b-1) = a^2 - 1 < a*a
    otherwise (a - 1 >= b as a is always larger)
      (a+1)*(b-1) = a*b - a + b - 1 =< a*b

    On each iteration new a*b will be less,
    continue until we can, or 2nd condition is still met
  """
  while (a+1) * (b-1) >= N and isok(a+1, b-1):
    a, b = a + 1, b - 1

  return (a, b)

def decomposite(N):
  a = int(sqrt(N))
  b = a

  # N is square, result is ok
  if a * b >= N:
    return (a, b)

  a += 1

  if a * b >= N:
    return improve(a, b, N)

  return improve(a, b+1, N)

def test(N):
  (a, b) = decomposite(N)

  print "%d decomposed as %d * %d = %d" % (N, a, b, a*b)

[test(x) for x in [99, 100, 101, 20, 21, 22, 23]]

输出

99 decomposed as 11 * 9 = 99
100 decomposed as 10 * 10 = 100
101 decomposed as 13 * 8 = 104
20 decomposed as 5 * 4 = 20
21 decomposed as 7 * 3 = 21
22 decomposed as 6 * 4 = 24
23 decomposed as 6 * 4 = 24

答案 1 :(得分:1)

我认为这可能有效(你的条件有些含糊不清)。这个解决方案有点类似于其他解决方案,基本上产生几乎是方形的矩形矩阵。 你可能需要证明A + 2不是最佳条件

A0 = B0 = ceil (sqrt N)
A1 = A0+1
B1 = B0-1
if A0*B0-N > A1*B1-N: return (A1,B1)
return (A0,B0)

如果第一个条件占优势(并且不使用第二个条件),这是解决方案

A0 = B0 = ceil (sqrt N)
if A0*B0==N: return (A0,B0)
return (N,1)

其他条件变化将介于

之间

答案 2 :(得分:0)

A = B = ceil (sqrt N)
相关问题