循环计算 - 可除整数之和

Loop computation - Sum of integers that are devidable

我正在寻找一种方法来计算 1 到 20 之间可以被 2、3 或 5 整除的整数之和。

我用 1 到 20 的整数创建了一个数组。 Y= np.arange(1, 21, 1)

我知道计算和检查应该在循环中完成,可能是 if 循环检查 Y 是否可以除以 2、3 或 5,然后如果语句为真,则使真语句相加。我该怎么做?

我按照下面的方法试了,但是有错误

for i in np.arange(1, 21, 1):
    if i%2 ==0:
    print(x=0)
    else 
    print(x=i)

我认为上面的代码会给我一个向量 x,如果它不能被 to 除以,则范围内的 I 为 0,如果它可以被 2 除,则为整数 i 的值。 我该如何修正这个错误?

您可以使用取模运算符:

5%5 = 0
5%3=2
4%2 = 0

所以只要 x % n 不等于 0 就不可整除

如何检查一个数是否可​​以被另一个数整除?简单,只需使用 % 运算符检查 a 除以 b 的余数是否为零,检查 here.

示例:

def is_dividable_by_2(n):
    return bool(n % 2 == 0)


num = 5

if is_dividable_by_2(num):
    print('%s is dividable by two' % num)
else:
    print('%s is not dividable by two' % num)

num = 4
if is_dividable_by_2(num):
    print('%s is dividable by two' % num)
else:
    print('%s is not dividable by two' % num)

输出:

$ python dividable.py 
5 is not dividable by two
4 is dividable by two

利用您已经在使用 numpy 的优势,您可以执行以下操作:

def get_divisible_by_n(arr, n):
    return arr[arr%n == 0]

x = np.arange(1,21)

get_divisible_by_n(x, 2)
#array([ 2,  4,  6,  8, 10, 12, 14, 16, 18, 20])

get_divisible_by_n(x, 5)
#array([ 5, 10, 15, 20])

一个数除以n的条件是number%n == 0。当您执行 arr[arr%n == 0] 时,您将条件应用于数组的每个位置。