算法设计之Project Euler 01:Multiples of 3 and 5

一、问题

Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

二、问题描述

如果一个数小于10,且能被3和5整除,这样的数有3,5,6,9,他们的和一共是23.

请找出小于1000,且能被3和5整除的数的和。

答案为:233168

三、第一遍刷Project Euler

思路比较简单,直接遍历1000以内的所有数,然后累加能被3和5整除的数。

python版本的代码:

def multiples(x):
    num = 0
    for i in range(x):
        if i%3==0 or i%5==0:
            num += i
    return num

print(multiples(1000))

C++版本的代码:

#include<iostream>

void multiples(int x)
{
	int num = 0;
	for (int i = 0; i < x; i++)
	{
		if ((i%3==0)||(i%5==0))
		{
			num += i;
		}
	}
	std::cout << num << std::endl;
	system("pause");
}

void main()
{
	multiples(1000);
}

猜你喜欢

转载自blog.csdn.net/z704630835/article/details/82588769