获取一个数的因数 [英] Get factors of a number

查看:68
本文介绍了获取一个数的因数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到给定数 (n) 的两个因数 (x, y),使得:

I need to get two factors ( x, y ) of a given number ( n ) such that:

  • x * y <= n
  • x * y 应该尽可能接近 n
  • x 和 y 应尽可能彼此靠近.

示例:

  • n = 16 => x = 4,y = 4
  • n = 17 => x = 4,y = 4
  • n = 18 => x = 6,y = 3
  • n = 20 => x = 5,y = 4

任何语言都可以,但最好是 php.

Any language will do but preferably php.

编辑——澄清

我想创建一个矩形,x 单位宽 * y 单位高,使其面积尽可能接近 n.x 和 y 必须是整数.如果 n 是素数,则 n - 1 的因数是可以接受的.

I want to create a rectangle, x units wide * y units tall such that its area is as close to n as possible. x and y must be integers. If n is a prime number then factors of n - 1 are acceptable.

推荐答案

您的说明不够准确.你说你想要因子,但在你的测试用例中 4 不是 17 的因子

Your specifications weren't quite exact enough. You stated that you wanted factors, yet in your test case 4 is not a factor of 17

以下伪代码优先考虑一个因素是精确

The following pseudo code works prioritizing that one factor is exact

for i in range(ceiling(sqrt(n)), 1){
    if ( n modulo i ) == 0 {
          x = i
          y = round(n/i)
    }
}

简单的 sqrt 语句可以确保数字尽可能接近,但不能保证它们是因数.

Where as a simple sqrt statement will work for ensuring that the numbers are as close together as possible, but doesn't guarantee that they are factors.

x = y = round( sqrt(n) )

这篇关于获取一个数的因数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆