decompose a numeric value

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

Thu Oct 04, 2012 1:21 pm

it looks like you're trying to do a form of prime factorization. there are a number of ways to do that, but typically the algorithm is going to be the same regardless of the language you're implementing it in. Just think of how you'd do it manually.

personally, i'd create a Sieve of Eratosthenes (look it up if you're not familiar with it, as sieves make identifying and working with primes a lot more efficient) with the max value being your initial number $n.

That will very quickly give you a list of prime numbers lower than your number. Then just step backwards through each prime number ($p) to see if $n mod $p == 0. If that condition is met, your $result_string .= $n/$p .'x'.$p and $n = $n-($p*($n/$p)). then lather rinse repeat until $n = 0 and your result string will be formatted the way you want it to.

Post Reply