Question

So I am currently trying to code a program that will find the prime factorization of any number. I have been successful in doing so, I am just getting caught up on having it be represented properly. For instance, the prime factorization of 82944 is (2^10)*(3^4).

My program successfully finds the prime factorization...just in a messy way. I am close to representing it properly with the following:

$unique_factors = array_unique($f);
foreach($unique_factors as $factors){
    foreach(array_count_values($f) as $count){
        echo $factors . "<sup>" . $count . "</sup>";
    }
}

However, this outputs (2^10)(2^4)(3^10)(3^4)

(The array $f is the array containing 2,2,2,2,2,2,2,2,2,2,3,3,3,3)

Was it helpful?

Solution

You don't need the outer loop - array_count_values returns (from the manual page) "an array using the values of array as keys and their frequency in array as values."

So you just need to do this:

foreach(array_count_values($f) as $key=>$count){
    echo "$key<sup>$count</sup>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top