PHP Program to Find All Prime Numbers in a Given Interval
Last Updated :
17 Jan, 2024
Prime numbers are fundamental in the field of mathematics and computer science. A prime number is defined as a natural number greater than 1 and is divisible by only 1 and itself.
In this article, we will explore how to write a PHP program to find all prime numbers within a given interval.
Using Trial Division Method
The trial division method is a straightforward way to check whether a number is prime. We iterate through all numbers in the given interval and test each number for primality.
PHP
<?php
function isPrime( $num ) {
if ( $num < 2) {
return false;
}
for ( $i = 2; $i <= sqrt( $num ); $i ++) {
if ( $num % $i == 0) {
return false;
}
}
return true;
}
function findPrimeNums( $start , $end ) {
$primes = [];
for ( $i = $start ; $i <= $end ; $i ++) {
if (isPrime( $i )) {
$primes [] = $i ;
}
}
return $primes ;
}
$start = 10;
$end = 50;
$primeNumbers = findPrimeNums( $start , $end );
echo implode( ', ' , $primeNumbers );
?>
|
Output
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
Using Sieve of Eratosthenes
The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers to a given limit. It works by iteratively marking the multiples of each prime, starting from 2.
PHP
<?php
function findPrimeNums( $n ) {
$isPrime = array_fill (2, $n , true);
for ( $i = 2; $i * $i <= $n ; $i ++) {
if ( $isPrime [ $i ]) {
for ( $j = $i * $i ; $j <= $n ; $j += $i ) {
$isPrime [ $j ] = false;
}
}
}
return array_keys ( array_filter ( $isPrime ));
}
$start = 10;
$end = 50;
$primeNums = findPrimeNums( $end );
$primeNumsInRange = array_filter ( $primeNums ,
function ( $num ) use ( $start , $end ) {
return $num >= $start && $num <= $end ;
});
echo implode( ', ' , $primeNumsInRange );
?>
|
Output
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
Share your thoughts in the comments
Please Login to comment...