如何检查一个数字是否可以被另一个数字整除(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
当且仅当<$ c $时,
才会计算为真c> 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屋!