【欧拉计划1】Multiples of 3 and 5

欢迎访问我的新博客:http://www.milkcu.com/blog/

原文地址:http://www.milkcu.com/blog/archives/1367311260.html

前言

昨天发现了Project Euler,一个不错的Project,同时改善了数学、计算机、英语方面的思维和能力。

每天做一点也是正确的选择,今天就从第一题开始耕耘吧。

这个项目当你提交答案后,会得到一份题目剖析,应作者的希望,那pdf就不分享了。

Please do not deprive others of going through the same process by publishing your solution outside Project Euler.

题目描述

原文:

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.

中文表达如下:

3和5的公倍数

如果我们列出10以下3和5的公倍数,我们得到3,5,6,9.这些公倍数的和是23.
求出1000以下3和5的公倍数的和。

简单方法

一种简单的思路如下(C语言实现):

# include <stdio.h>
# define NUM 1000
int main(void)
{
	int n;
	int i;
	int sum;
	
	sum = 0;
	for(n = 1; n < NUM; n++) {
		if(n % 3 == 0 || n %5 == 0) {
			sum += n;
		}
	}
	printf("%d", sum);
}

但是我们仔细想一下,当数量级逐步增大的过程中,也许我们需要更好的方法。

更有效的方法

我们可以计算(3的公倍数的和 + 5的公倍数的和 - 15的公倍数的和),再利用1+2+3+...+p=0.5*p*(p+1)求和公式,进一步减少时间复杂度:

# include <stdio.h>
# define NUM 1000
int sumdiv(int n);
int main(void)
{
	printf("%d", sumdiv(3) + sumdiv(5) - sumdiv(15));
}
int sumdiv(int n)
{
	int i;
	
	i = (NUM - 1) / n;    //注意边界值 
	return n * 0.5 * i * (1 + i);
}

时间复杂度从O(n)降到O(1)。

后记

这题的思路不难理解,但是对于曾经的我,还缺少灵活运用,首先想到的是简单方法。

提交答案后,看到Congratulations我也更兴奋了。

Congratulations, the answer you gave to problem 1 is correct.

我也是28840分之一了。

原文地址:https://www.cnblogs.com/milkcu/p/3808899.html