如何检查给定数N,N ^ 2是否可以表示为两个非零整数的平方和?

时间:2015-10-10 05:42:29

标签: algorithm math

给定数N,我怎样才能知道N ^ 2是否可以表示为两个非零整数的平方和。例如,如果N = 10,则10 ^ 2可以表示为(6 ^ 2)+(8 ^ 2)。我已经读过这样的数字N可以表示为4k + 1但是甚至9表示该表达式,但81不能表示为两个整数的平方和。什么是正确的方法?

3 个答案:

答案 0 :(得分:1)

你想要的数字是毕达哥拉斯三元组的斜边(“c”值),OEIS中的A009000系列。那里的评论指出,一个数字是一个斜边,当且仅当它被4k + 1形式的至少一个素数整除时。因此,您可以通过获取其素数因子来检查数字是否是斜边,然后查看这些素数中的任何一个在除以4时是否具有余数1。

在你的例子中,81不符合条件,因为它唯一的素数因子是3. 81可以被9整除,但9不是素数。

答案 1 :(得分:1)

使用此对象,“c”是您的数字如果运行后检查“a”和“b”不等于null checkPi()方法a,b和c是毕达哥拉斯三元组。

<?php

Class PithgorasTriplesDetector {

    /**
     * 
     * @var type 
     */
    private $a, $b, $c;

    /**
     *
     * @var type 
     */
    private $check_numbers = array();

    /**
     * 
     * @param type $c
     */
    public function __construct($c) {
        $this->c = $c;
        $this->check_numbers = range(1, $this->c);
    }

    /**
     * 
     * @return boolean
     */
    public function checkPi() {
        $counter = count($this->check_numbers);
        $c_pow = pow(2, $this->c);
        for ($index = $counter - 1; $index >= 0; $index--) {
            for ($index2 = $index; $index2 > 0; $index2--) {
                if ($this->calcAB($index, $index2) == $c_pow) {
                    $this->a = $index;
                    $this->b = $index2;
                    return true;
                }
                if ($this->calcAB($index, $index2) > $c_pow) {
                    continue;
                } else {
                    return false;
                }
            }
        }
    }

    /**
     * 
     * @param type $a
     * @param type $b
     * @return type
     */
    public function calcAB($a, $b) {
        return pow(2, $a) + pow(2, $b);
    }

    function getA() {
        return $this->a;
    }

    function getB() {
        return $this->b;
    }

    function getC() {
        return $this->c;
    }

    function setA($a) {
        $this->a = $a;
    }

    function setB($b) {
        $this->b = $b;
    }

    function setC($c) {
        $this->c = $c;
    }

}

答案 2 :(得分:0)

听起来像毕达哥拉斯计算器。

此链接可以帮助您,所有PYTHAGOREAN TRIPLES

http://www.tsm-resources.com/alists/trip.html

相关问题