你如何检查一个数字是否可以被另一个数字整除(Python)? [英] How do you check whether a number is divisible by another number (Python)?
问题描述
我需要测试从 1 到 1000 的每个数字是 3 的倍数还是 5 的倍数.我认为这样做的方法是将数字除以 3,如果结果是整数那么它将是 3 的倍数.与 5 相同.
I need to test whether each number from 1 to 1000 is a multiple of 3 or a multiple of 5. The way I thought I'd do this would be to divide the number by 3, and if the result is an integer then it would be a multiple of 3. Same with 5.
如何测试数字是否为整数?
How do I test whether the number is an integer?
这是我当前的代码:
n = 0
s = 0
while (n < 1001):
x = n/3
if isinstance(x, (int, long)):
print 'Multiple of 3!'
s = s + n
if False:
y = n/5
if isinstance(y, (int, long)):
s = s + n
print 'Number: '
print n
print 'Sum:'
print s
n = n + 1
推荐答案
您可以使用模数运算符 %
You do this using the modulus operator, %
n % k == 0
当且仅当 n
是 k
的精确倍数时才计算为真.在初等数学中,这被称为除法的余数.
evaluates true if and only if n
is an exact multiple of k
. In elementary maths this is known as the remainder from a division.
在您当前的方法中,您执行除法,结果将是
In your current approach you perform a division and the result will be either
- 如果使用整数除法,则始终为整数,或
- 如果使用浮点除法,则始终为浮点数.
这只是测试可分性的错误方法.
It's just the wrong way to go about testing divisibility.
这篇关于你如何检查一个数字是否可以被另一个数字整除(Python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!