【每日一题0913】求倍数之和

:woman_mage:给定一个目标整数n,计算0到n之间(不含n自身),所有是3或者5的倍数的数字之和。例如,我们列举10以内3或者5的倍数的整数,则会得到3,5,6,9。它们的总和是23。
备注:如果一个数同时是3和5的倍数,则只统计1次。所有数字都是正整数。如果输入的n是负数,则返回0。

示例
输入:4,输出:3。因为满足条件的数字只有3。
输入:6,输出:8。因为满足条件的数字是3和5。

def multiples_sum(n: int) -> int:
    pass

assert multiples_sum(4) == 3
assert multiples_sum(6) == 8
assert multiples_sum(15) == 45
assert multiples_sum(0) == 0
def multiples_sum(n):
    sum = 0
    if n < 0:
        return 0
    for i in range(n):
        if i % 3 == 0 or i % 5 == 0:
            sum += i
    return sum

同时是3或5只统计一次

def multiples_sum(n: int) -> int:
    sum = 0
    for i in range(n):
        if i%3==0 or i%5==0:
            sum += i
    return sum
def multiples_sum(n: int) -> int:
    sum = 0
    temp = set()
    if n < 0:
        return 0
    else:
        for i in range(n):
            if i % 3 == 0 or i % 5 == 0:
                temp.add(i)
        for x in temp:
            sum += x
    return sum
 public Integer multiplesSum(Integer integer) {
        int res = 0;
        if (integer <= 0) {
            return 0;
        } else {
            for (int i = 0; i < integer; i++) {
                if (i % 3 == 0 || i % 5 == 0) res += i;
            }
        }
        return res;
    }
    @Test
    public void testMultiplesSum(){
        assert multiplesSum(4).equals(3);
        assert multiplesSum(6).equals(8);
        assert multiplesSum(15).equals(45);
        assert multiplesSum(0).equals(0);
    }
def multiples_sum(n: int) -> int:
    result = 0
    if not isinstance(n, int) or n < 0:
      return 0
    for i in range(n):
      if i % 3 == 0 or i % 5 == 0:
        result += i
    return result

assert multiples_sum(4) == 3
assert multiples_sum(6) == 8
assert multiples_sum(15) == 45
assert multiples_sum(0) == 0
def multiples_sum(n: int) -> int:
    n = n - 1
    m_3 = n - n % 3
    m_5 = n - n % 5
    m_15 = n - n % 15
    sum_3 = (0 + m_3) * (m_3 // 3 + 1) / 2
    sum_5 = (0 + m_5) * (m_5 // 5 + 1) / 2
    sum_15 = (0 + m_15) * (m_15 // 15 + 1) / 2
    return int(sum_3 + sum_5 - sum_15)
def multiples_sum(n: int) -> int:
    if n < 0:
        return 0
    total = 0
    for i in range(n):
        if i % 3 == 0 or i % 5 == 0:
            total += i
        elif i % 3 == 0 and i % 5 == 0:
            total -= i
    return total

assert multiples_sum(4) == 3
assert multiples_sum(6) == 8
assert multiples_sum(15) == 45
assert multiples_sum(0) == 0
关闭