欧拉项目之求数值的和
来源:互联网 发布:淘宝店铺名字 大全 编辑:程序博客网 时间:2024/05/01 02:00
第一题:
描述:
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.
(先思考,如果有兴趣先编程试试,然后才看下面的内容)
分析:
由于是第一题,所以非常简单,我稍稍分析一下
我们可以看看不超过20的数中3,5的倍数列表:3, 5, 6, 9, 10, 12, 15, 18, 20
很明显其可以撤成两类 3, 6, 9, 12, 15, 18 和 5, 10, 15, 20
他们分别是以3为首项3为等差的等差数列 以及 以5为首项5为等差的等差数列。或者理解成3的倍数的数列,以及5的倍数的数列
由于两个数列中存在3和5的公倍数,即为15,15*2,15*3......,结果将其减去即可。
以下是实现程序:
public class Test{
public void main(String args[]){
int sum=0;
int n=1000-1;
sum+=(n/3)*(999+3)+(n/5)*(995+5)-(n/15)*(n/15);
}
}
当然等差数列的求和过程可以封装成一个函数,那就更清晰了。
第二题:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
一个Fibonacci数列,求4百万以下偶数的和。
public class Test {
public static void main(String args[]){
Test t=new Test();
t.a();
t.b();
}
public void a(){
int sum=2;
int a1,a2,a3=0;
a1 = 1;
a2 = 2;
int i=0;
while(a3<4000000){
a3 = a1+a2;
a1 = a2;
a2 = a3;
i++;
if(0==a3%2){
sum+=a3;
}
}
System.out.println(i);
}
public void b(){
int x=1,y=2;
int z=0,q=0;
int sum=2;
z=x+y; //第一个奇数
q=y+z; //第二个奇数
int i2=0;
while(z+q<4000000){
sum+=(z+q);
int temp=z+q;
z=temp+q;
q=temp+z;
i2++;
}
System.out.println(i2);
}
}
函数a()是我在网上看到一般的做法,函数b()是我自己的做法,算法复杂度为a()的1/3,而且是单纯的加法运算,这是计算机的强项。主要的想法是:1,2,3,5,8,13,21,34,。。。。。, 从2开始每个两个奇数就得到要加的偶数,所以我们只需要把这两个奇数(z,q)算出来就可以算出下一个要加的偶数(z+q),每次循环前进三个数,而a()每次循环只先前移了一个数。
看了看别人写的代码,还有不少人根据数列的规律优化了下.
规律大致是这样的
Fibonacci 数列 为(x=y=1)
x,y,x+y,x+2y,2x+3y,3x+5y...
红色的是偶数.
这样代码就可以写成下面
view plaincopy to clipboardprint?
def calcE():
x = y = 1
sum = 0
while (sum < 1000000):
sum += (x + y)
x, y = x + 2 * y, 2 * x + 3 * y
return sum
- 欧拉项目之求数值的和
- 仪仗队 求n以内欧拉函数值的和
- 间断初值双曲守恒问题的Lax-Friedrichs和后向欧拉数值解法
- 欧拉项目010:2000000以内的素数和
- 数值计算之二:迭代法求线性方程的解
- 求1~n的欧拉函数
- 求乘法数值和符号
- 求数值型数组的子数组和最大值
- diff和gradient求数值近似导数的异同
- VC++求最大数值和表达式的一些问题处理
- HDU 1452 欧拉定理的应用+求幂级数的因子和
- poj-3090 Visible Lattice Point 求前n欧拉函数值的和
- 求数值的整数次方。
- 求数值的整数次方
- 求数值的整数次方
- 【数值分析】常微分方程数值解:欧拉公式
- 【数值分析】常微分方程数值解:欧拉公式
- 微分方程数值解法(欧拉方法)
- AT&T汇编 helloworld实例
- Windows的消息驱动机制
- 虚拟目录继承根目录web.config 设置
- the application has stopped unexpected。please try again
- Android消息处理机制
- 欧拉项目之求数值的和
- Android中的Button注册监听
- 使用Hibernate主键产生器生成主键
- C# 使用SerialPort控件用类及线程实现串口通信
- 关于signed和unsigned的隐秘bug
- QString string转换
- SPD中隐藏固定的行~
- 如何在命令行设置IP
- java接口中能申明私有成员么?接口能不能实例化?