Skip to content

Commit 70def3f

Browse files
committed
Add Integer::isPrime.
1 parent 4d4bfad commit 70def3f

File tree

3 files changed

+875
-0
lines changed

3 files changed

+875
-0
lines changed

src/NumberTheory/Integer.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,39 @@ function ($m) use ($√n) {
349349
return [];
350350
}
351351

352+
/**
353+
* Primality test (prime number test)
354+
* https://en.wikipedia.org/wiki/Primality_test
355+
*
356+
* Determines whether a number is a prime number.
357+
*
358+
* @param int $n
359+
*
360+
* @return bool
361+
*/
362+
public static function isPrime(int $n): bool
363+
{
364+
if ($n <= 1) {
365+
return false;
366+
}
367+
368+
if ($n === 2 || $n === 3) {
369+
return true;
370+
}
371+
372+
if ($n % 2 === 0 || $n % 3 === 0) {
373+
return false;
374+
}
375+
376+
for ($i = 5; $i <= \sqrt($n); $i += 6) {
377+
if ($n % $i === 0 || $n % ($i + 2) === 0) {
378+
return false;
379+
}
380+
}
381+
382+
return true;
383+
}
384+
352385
/**
353386
* Prime factorization
354387
* The prime factors of an integer.

tests/NumberTheory/IntegerAxiomsTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
* Axioms tested:
1616
* - Coprime
1717
* - lcm(a, b) = ab
18+
* - Prime factorization
19+
* - All primes
1820
*/
1921
class IntegerAxiomsTest extends \PHPUnit\Framework\TestCase
2022
{
@@ -109,4 +111,18 @@ public function dataProviderForCoprime(): array
109111
[29, 30],
110112
];
111113
}
114+
115+
/**
116+
* Axiom: Prime factorization produces only primes
117+
* @return void
118+
*/
119+
public function testPrimeFactorizationAllPrimes(): void
120+
{
121+
for ($i = 2; $i < 10000; $i++) {
122+
$primes = Integer::primeFactorization($i);
123+
foreach ($primes as $prime) {
124+
$this->assertTrue(Integer::isPrime($prime));
125+
}
126+
}
127+
}
112128
}

0 commit comments

Comments
 (0)