What would be the most optimized method for finding the highest multiple of X in Y?
As in, if I have the value 25 and I want to know the highest multiple of 6 in it, I should get 24.
My brain is not working and I'll likely just loop until I get there which is gonna be too slow for the values I'm working with.
Simple Math Question
Moderator: General Moderators
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Ha, yet again I solve my own problem after posting 
HCF == Highest Common Factor
Code: Select all
function get_hcf($value, $factor)
{
return ($value - ($value%$factor));
}
echo get_hcf(25, 6); //24- Skittlewidth
- Forum Contributor
- Posts: 389
- Joined: Wed Nov 06, 2002 9:18 am
- Location: Kent, UK
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Yeah I was thinking the same thing before I posted. I knew modulus (%) gives the remainder left over if you divide X by Y but my brain hadn't quite processed the thought that all I needed to do was then remove that from the original value 
This was a for base64 encoding algorithm if anybody wondered what I was doing, all encoded strings must be divisble by 4.
This was a for base64 encoding algorithm if anybody wondered what I was doing, all encoded strings must be divisble by 4.
-
crazytopu
- Forum Contributor
- Posts: 259
- Joined: Fri Nov 07, 2003 12:43 pm
- Location: London, UK
- Contact:
Another way:
Code: Select all
public int findMultiple(int no, int multipleOf)
{
int result = no/multipleOf;
return result*multipleOf;
}- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
That's an elegant solution. Incidentally though, all those brackets are redundant. % is done before - and return doesn't require brackets.d11wtq wrote:Code: Select all
function get_hcf($value, $factor) { return ($value - ($value%$factor)); } echo get_hcf(25, 6); //24
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US