Math function to find the biggest multiple of a number within a range

  • A+
Category:Languages

I want to know if there is a math expression that I can use to find this relation between two numbers.

Some examples of the input and expected output are below:

Input    Multiple   Result 4        3          3 6        3          6 8        3          6 4        4          4 12       4          12 16       5          15 

Also, the expressions below from Wolfram Alpha show me the expected result but since they don't expand on the explanation on how to do it I can't learn from them...

Biggest multiple of 4 from 10

Biggest multiple of 4 from 12

 


You can employ modulo for this. For example, to calculate the biggest multiple of 4 that is less or equal than 13:

13 % 4 = 1 13 - 1 = 12 

in python, that could look like this:

def biggest_multiple(multiple_of, input_number):     return input_number - input_number % multiple_of 

So you use it as:

$ biggest_multiple(4, 9) 8 $ biggest_multiple(4, 12) 12 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: