Ask about general coding issues or problems here.
Moderators: macek, egami, gesf
First sorry for my bad English. I'm newbie in PHP so if my question previously asked please forgive me because I dont know what keyword I should search about.
I have a form which gets some numeric values form visitors. The question is how can I decompose a numeric value to multiple from 1, 2 and 3 in any cases and give back to them as choices.
For example I have "5":
1-> 5= 2x2 + 1x1
2-> 5= 1x3 + 1x2 + 1x1
3-> 5= 5x1
Thanks in advance.
- New php-forum User
- Posts: 1
- Joined: Thu Oct 04, 2012 1:24 am
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.
- php-forum Fan User
- Posts: 838
- Joined: Mon Oct 01, 2012 12:32 pm
Return to PHP coding => General
Who is online
Users browsing this forum: No registered users and 2 guests