Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Largest multiple of n lower than x

Most pythonic way avoiding for loops 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 am doing a for loop till I don't go over x now

like image 233
Guido Avatar asked Dec 19 '25 06:12

Guido


1 Answers

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.

like image 161
Mad Physicist Avatar answered Dec 21 '25 02:12

Mad Physicist