【题目一】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的倍数的数字之和。
【思路一】直接一个for循环,遍历[3,1000),找出3和5的倍数,累加即可。
【代码一】
void test1()
{
int sum = 0;
for (int i = 3; i < 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
sum += i;
}
cout << sum << endl;
}
【思路二】我们容易知道1000中3的倍数可以表示为3*n,其中n属于[1,1000/3)。进而1000中3的倍数的和为3*n*(n+1)/2,据此可以得到
1000中5的倍数的和,之后还需要减去1000中3和5的公倍数15的和。据此思路,编码如下:
【代码二】
void test1()
{
int n1 = 999 / 3;
int n2 = 999 / 5;
int n3 = 999 / 15;
int sum =(n1 + 1)*n1 / 2 * 3 + (n2 + 1)*n2 / 2 * 5 - (n3 + 1)*n3 / 2 * 15;
cout << sum << endl;
}
【答案】运行程序后,最终结果为 233168。