Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

math

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

like image 367
Ícaro Avatar asked Dec 13 '25 08:12

Ícaro


2 Answers

try with // and % operators!

for //, you would do

Result = (Input // Multiple) * Multiple

This way you get how many times Multiple Fits into Input - this number is then multiplied with the Multiple itself and therefore gives you the expected results!

EDIT: how to do it with modulo %?

Result = Input - (Input % Multiple)

taken from MCO's answer!

like image 188
Cut7er Avatar answered Dec 15 '25 23:12

Cut7er


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
like image 44
MCO Avatar answered Dec 15 '25 22:12

MCO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!