Find the largest multiple of n lower than x

  • A+

What would be the more pythonic way to find the largest number multiple of n but lower than an upperbound x?

Practical example:

n = 48  x = 2636  

48 * 54 = 2592 is the nearest.

I would do a for loop till I don't go over x. What are nicer alternatives?


The simplest way is probably using //:

(x // n) * n 

If the number has to be strictly less than x, use x - 1 instead:

((x - 1) // n) * n 

The expression x // n is the floor division of x by n, discarding any remainder.


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