diff --git a/Math/Number/Integer.php b/Math/Number/Integer.php index 884bfd717..594d1ad99 100644 --- a/Math/Number/Integer.php +++ b/Math/Number/Integer.php @@ -1,9 +1,87 @@ -class Integer implements Number { -public function isPrime() { + $m) { + $n -= $m; + } else { + $m -= $n; + } + } + } -public function getIntegerFactorization() { + public static function trialFactorization(int $value) + { + if ($value < 2) { + return []; + } -} + $factors = []; + $primes = Prime::sieveOfEratosthenes((int) $value**0.5); + + for($primes as $prime) { + if($prime*$prime > $value) { + break; + } + + while($value%$prime === 0) { + $factors[] = $prime; + $value /= $prime; + } + } + + if($value > 1) { + $factors[] = $value; + } + + return $factors; + } + + public static function pollardsRho($value, $x = 2, $factor = 1, $cycleSize = 2, $xFixed = 2) + { + while($factor === 1) { + for($i = 1; $i < $cycleSize && $factor <= 1; $i++) { + $x = ($x*$x+1)%$value; + $factor = self::greatestCommonDivisor($x-$xFixed, $value); + } + + $cycleSize *= 2; + $xFixed = $x; + } + + return $factor; + } + + public static function fermatFactor(int $value) + { + $a = $value; + $b2 = $a*$a - $value; + + while(abs((int) round(sqrt($b2), 0) - sqrt($b2)) > 0.0001) { + $a += 1; + $b2 = $a*$a - $value; + } + + return $a - sqrt($b2); + } } \ No newline at end of file diff --git a/Math/Number/Natural.php b/Math/Number/Natural.php index ce1b72ba3..7e34819ad 100644 --- a/Math/Number/Natural.php +++ b/Math/Number/Natural.php @@ -1,2 +1,9 @@ -class Natural implements Number { += 0; + } } \ No newline at end of file diff --git a/Math/Number/Numbers.php b/Math/Number/Numbers.php index 13330171d..bf8b1c8b2 100644 --- a/Math/Number/Numbers.php +++ b/Math/Number/Numbers.php @@ -142,28 +142,4 @@ class Numbers return $count; } - - /** - * Greatest common diviser. - * - * @param int $n Number one - * @param int $m Number two - * - * @return int - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function greatestCommonDivisor(int $n, int $m) : int - { - while (true) { - if ($n === $m) { - return $m; - } if ($n > $m) { - $n -= $m; - } else { - $m -= $n; - } - } - } } \ No newline at end of file diff --git a/Math/Number/Prime.php b/Math/Number/Prime.php index 7a8161289..6ddf2846b 100644 --- a/Math/Number/Prime.php +++ b/Math/Number/Prime.php @@ -116,4 +116,45 @@ class Prime return true; } + + public static function sieveOfEratosthenes(int $n) : array + { + $number = 2; + $range = range(2, $n); + $primes = array_combine($range, $range); + + while ($number*$number < $n) { + for ($i = $number; $i <= $n; $i += $number) { + if ($i == $number) { + continue; + } + + unset($primes[$i]); + } + + $number = next($primes); + } + + return $primes; + } + + public function isPrime(int $n) : bool + { + $i = 2; + + if ($n === 2) { + return true; + } + + $sqrtN = sqrt($n); + while ($i <= $sqrtN) { + if ($n % $i === 0) { + return false; + } + + $i++; + } + + return true; + } } \ No newline at end of file