Page 1 of 1

Simple Math Question

Posted: Thu Dec 21, 2006 6:06 am
by Chris Corbyn
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.

Posted: Thu Dec 21, 2006 6:12 am
by Chris Corbyn
Ha, yet again I solve my own problem after posting :P

Code: Select all

function get_hcf($value, $factor)
{
    return ($value - ($value%$factor));
}

echo get_hcf(25, 6); //24
HCF == Highest Common Factor

Posted: Thu Dec 21, 2006 6:16 am
by Skittlewidth
I was about to suggest something using % but not being much of a mathematician myself I couldn't remember how to use it to do what you wanted!

Glad you figured it out (and strangely pleased with myself for getting halfway to the answer!)

Posted: Thu Dec 21, 2006 6:29 am
by Chris Corbyn
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.

Posted: Thu Dec 21, 2006 8:27 am
by crazytopu
Another way:

Code: Select all

public int findMultiple(int no, int multipleOf)
    {
        
        int result = no/multipleOf;
        
        return result*multipleOf;
        
     }

Posted: Thu Dec 21, 2006 10:34 am
by Ollie Saunders
d11wtq wrote:

Code: Select all

function get_hcf($value, $factor)
{
    return ($value - ($value%$factor));
}

echo get_hcf(25, 6); //24
That's an elegant solution. Incidentally though, all those brackets are redundant. % is done before - and return doesn't require brackets.

Posted: Thu Dec 21, 2006 3:44 pm
by Christopher
Rather than doing get_hcf($value, $factor), couldn't you just do floor($value / $factor)?