PHP Program to Print All Prime Factors of a Given Number
Last Updated :
27 Feb, 2024
Prime factors of a number are the prime numbers that divide the given number exactly. Finding prime factors is a common task in number theory and has applications in cryptography and algorithm design. In this article, we will discuss efficient ways to print all prime factors of a given number in PHP.
Print All Prime Factors of a Given Number using Trial Division
The simplest method to find prime factors is by trial division. We start from the smallest prime number, 2, and divide the given number as long as it is divisible. We then move to the next prime numbers and repeat the process.
PHP
<?php
function primeFactors( $n ) {
while ( $n % 2 == 0) {
echo "2 " ;
$n = $n / 2;
}
for ( $i = 3; $i <= sqrt( $n ); $i += 2) {
while ( $n % $i == 0) {
echo "$i " ;
$n = $n / $i ;
}
}
if ( $n > 2) {
echo "$n" ;
}
}
$number = 315;
primeFactors( $number );
?>
|
Explanation:
- The function
primeFactors
takes an integer $n
as input and prints its prime factors.
- First, it prints all the 2s that divide
$n
.
- Then, it iterates from 3 to the square root of
$n
, checking for divisibility by odd numbers (since even numbers have already been checked).
- If
$i
divides $n
, it prints $i
and divides $n
by $i
, repeating this process as long as $i
divides $n
.
- Finally, if
$n
is greater than 2, it means $n
is a prime number itself, and it is printed.
Print All Prime Factors of a Given Number using Sieve of Eratosthenes (Optimized for Multiple Queries)
If we need to find prime factors for multiple numbers, we can use the Sieve of Eratosthenes to precompute the smallest prime factor for each number up to a certain limit. This approach reduces the time complexity for each query.
PHP
<?php
function sieve( $n , & $spf ) {
for ( $i = 2; $i <= $n ; $i ++) {
$spf [ $i ] = $i ;
}
for ( $i = 2; $i * $i <= $n ; $i ++) {
if ( $spf [ $i ] == $i ) {
for ( $j = $i * $i ; $j <= $n ; $j += $i ) {
if ( $spf [ $j ] == $j ) {
$spf [ $j ] = $i ;
}
}
}
}
}
function primeFactors( $n , $spf ) {
while ( $n != 1) {
echo $spf [ $n ] . " " ;
$n = $n / $spf [ $n ];
}
}
$n = 315;
$prime_Factor = array ();
sieve( $n , $prime_Factor );
primeFactors( $n , $prime_Factor );
?>
|
Explanation:
- The
sieve
function precomputes the smallest prime factor ($spf
) for each number up to $n
.
- The
printPrimeFactors
function uses the precomputed $spf
array to print the prime factors of $n
efficiently.
- This approach is particularly useful when we need to find prime factors for multiple numbers, as the sieve computation is done only once.
Share your thoughts in the comments
Please Login to comment...