首页 > 解决方案 > 找到 2 个彼此尽可能接近的数字,当相乘时给出整数 X

问题描述

输入是要布局的单元格数,例如 X = 6。我需要将它们布局为正方形(或尽可能接近正方形的矩形)。对于 X = 6,矩形将是 3 列宽和 2 行高。

对于具有整数根的 X-es,例如 4 和 9,这很容易。列数和行数只是 X 的平方。获得其他场景的行数和列数的数学运算是什么?

标签: mathgeometry

解决方案


import numpy as np

def squarish(x):
    """returns rows and cols of a rectangle of x cells that best approximates a square"""
    # TODO add an isprime check and handle it as you want
    sqrt = np.sqrt(x)
    if int(sqrt) == sqrt:
        return int(sqrt), int(sqrt)

    rows = int(sqrt)
    while rows > 1:
        cols = x / rows
        if int(cols) == cols:
            return rows, int(cols)
        else:
            rows -= 1

推荐阅读