找到n低于x的最大倍数

Gui*_*ido 1 python algorithm math

找到最大数量n但低于上限的pythonic方法会是什么x

实际例子:

n = 48 
x = 2636 
Run Code Online (Sandbox Code Playgroud)

48 * 54 = 2592 是最近的.

我会做一个for循环,直到我不去x.什么是更好的替代品?

Mad*_*ist 10

最简单的方法可能是使用//:

(x // n) * n
Run Code Online (Sandbox Code Playgroud)

如果数字必须严格小于x,请使用x - 1:

((x - 1) // n) * n
Run Code Online (Sandbox Code Playgroud)

表达式x // nxby的n分层,丢弃任何余数.


Syr*_*ius 8

您可以使用模运算

x-(x%n)
Run Code Online (Sandbox Code Playgroud)

如果上限必须严格低于x使用

x - 1 -((x-1) % n)
Run Code Online (Sandbox Code Playgroud)