Product of prime

how do i get product of prime example for number 12 in php? in calculation we get product of prime for 12 is 2^2 x 3.

What is the algoritm you use to get to that answer?
Once you know that, all you have to do is program it.

hi thanx for replying. what i mean is, is there any code in php that can generate for example (3 x 3) for 9? it’s like when we set a variable with a number 9, and the output would be 3 x 3. is there any? if not, any idea how to do it?

As guido2004 said, if you know the algorithm you can write the code:

$prime = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);

$input = 9;
$test = $input;
$result = array();

foreach($prime AS $value) {
    while ($test % $value == 0) {
        $result[] = $value;
        $test = $test / $value;
        if($value > $test) { break 2; }
    }
}

echo "input= {$input}<br>\
";
echo "result= \
<pre>\
";
print_r ($result);
echo "</pre>\
";

Unfortunately this is not the best approach. Your’e using a static representation of what a prime number is rather than calculating it out. While it will be more expensive as you go higher, this will be more dynamic:

I was thinking exactly that! My next version won’t need that static set. :wink:

Calculating prime numbers from scratch gets to be pretty slow as the numbers get bigger. A practical algorithm would store the already calculated ones and it would add to the table as needed. An interesting problem. :wink:

A couple of PHP’s “built-in” functions between them may well cover what your intending to do:

  • gmp_nextprime() that will find the next prime number after the number given, it could be run in a loop with the function being given the last prime number it found as the number given.
  • gmp_prob_prime() will tell you if the number is probably a prime number.

I think the former would be your better bet being run in a loop to get an array of prime numbers then that array would be looped through and the product for each one calculated.

You might find that you have to enable the php_gmp extension first.

I’ve now written code that calculates the prime factors of any number and it also calculate the prime numbers it needs. Because calculating prime numbers is very time consuming, it saves the prime numbers for later reuse.

See The Learning Script