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.
Printable View
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.
As guido2004 said, if you know the algorithm you can write the code:
PHP 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>\n";
echo "result= \n<pre>\n";
print_r ($result);
echo "</pre>\n";
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:
http://tournasdimitrios1.wordpress.c...bers-with-php/
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. ;)
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