Simple Math Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Simple Math Question

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
User avatar
Skittlewidth
Forum Contributor
Posts: 389
Joined: Wed Nov 06, 2002 9:18 am
Location: Kent, UK

Post 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!)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
crazytopu
Forum Contributor
Posts: 259
Joined: Fri Nov 07, 2003 12:43 pm
Location: London, UK
Contact:

Post by crazytopu »

Another way:

Code: Select all

public int findMultiple(int no, int multipleOf)
    {
        
        int result = no/multipleOf;
        
        return result*multipleOf;
        
     }
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Rather than doing get_hcf($value, $factor), couldn't you just do floor($value / $factor)?
(#10850)
Post Reply