File tree Expand file tree Collapse file tree 3 files changed +875
-0
lines changed Expand file tree Collapse file tree 3 files changed +875
-0
lines changed Original file line number Diff line number Diff line change @@ -349,6 +349,39 @@ function ($m) use ($√n) {
349
349
return [];
350
350
}
351
351
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
+
352
385
/**
353
386
* Prime factorization
354
387
* The prime factors of an integer.
Original file line number Diff line number Diff line change 15
15
* Axioms tested:
16
16
* - Coprime
17
17
* - lcm(a, b) = ab
18
+ * - Prime factorization
19
+ * - All primes
18
20
*/
19
21
class IntegerAxiomsTest extends \PHPUnit \Framework \TestCase
20
22
{
@@ -109,4 +111,18 @@ public function dataProviderForCoprime(): array
109
111
[29 , 30 ],
110
112
];
111
113
}
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
+ }
112
128
}
You can’t perform that action at this time.
0 commit comments