【问题标题】:Algorithm to find positive and negative integer square roots (without given boundaries)查找正整数和负整数平方根的算法(没有给定边界)
【发布时间】:2018-04-08 05:22:29
【问题描述】:

我最近在面试时练习了很多算法。我想知道是否有另一种方法来解决这个问题。我以一种仅将其正数递增的方式编写它,因为我从基本数学中知道,两个负数相乘会得到一个正数,所以我只需要将满足条件的整数设为负数。

有没有一种方法可以优雅地在您不知道将两个负数相乘结果为正数的情况下编写此代码?

<?php

# Z = {integers}
# B = {x:x, x is an element of Z,  x^2 + 1 = 10}

$numNotFound = true;
$x = 0;
$b = [];

while ($numNotFound) {
    if ($x*$x + 1 == 10) {
        array_push($b, $x, $x*-1);
        $numNotFound = false;
    }
    $x++;
}

echo json_encode($b); #[3, -3]

【问题讨论】:

  • 我对您到底需要什么感到困惑?
  • 试试这个$ints = json_encode(range((PHP_INT_MAX * -1), PHP_INT_MAX)); ...或者不要...大声笑\s
  • @e_mam106 请查看更新后的答案。我认为这更符合您的要求。

标签: php algorithm discrete-mathematics


【解决方案1】:

更新

此解决方案不使用 -1 * -1 = 1 的事实。它将输出找到的第一个数字作为数组中的第一个元素。如果 x=-3 则 [-3,3] 或如果 x=3 [3,-3]。

$numNotFound = TRUE;
$x = 0;
$b = [];

Do{

  if ((pow($x, 2) + 1) === 10) {

    array_push($b, $x, 0 - $x); 
    $numNotFound = FALSE;

  }

  $x++;

}while($numNotFound);

echo json_encode($b); //[3, -3]

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 1970-01-01
    • 2014-07-14
    • 2014-03-06
    • 2015-03-04
    • 1970-01-01
    • 2017-12-21
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多