欧拉计划问题一matlab实现

Problem 1:Multiples of 3 and 5

if we list all the natural numbers blew 10 that multiples of 3 or 5, we get 3,5, 6 and 9,The sum of those multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000。

思路:

新建三个变量i,j,k。  i为3的倍数集合,j为5的倍数集合,k既是3的倍数,又是5的倍数集合,即为15的倍数集合.为什么要用到这个k呢?因为比如说15既是3的倍数又是5的倍数,即i里包含了15,j里也包含了15,那么就加了两次15,再减去一次就刚好了。

s = 0;
t = 0;
m = 0;
for i = 1:999
    if mod(i,3) == 0
            s = s + i;
    end
end
for j = 1:999
    if mod(j,5) == 0
        t = t + j;
    end
end
for k = 1:999
    if mod(k,15) == 0
        m = m + k;
    end
end
a = s + t - m;
a

代码可能不太简洁,抛砖引玉。希望大家多多交流!予以指正!

猜你喜欢

转载自blog.csdn.net/qq_38910271/article/details/82927825