求和:1 + 1/2! + 1/3! + 1/4! + 1/5! + ... + 1/50!
来源:互联网 发布:淘宝怎么改购买数量 编辑:程序博客网 时间:2024/06/09 23:46
package com.jnwork;public class SquenceTest { /** * 求和:1 + 1/2! + 1/3! + 1/4! + 1/5! + ... + 1/50! * @param args */ public static void main(String[] args) { System.out.println("递归求和:" + SquenceTest.getSquenceSum(50)); System.out.println("迭代求和:" + getSequenceSumByInterator(50)); } /** * 递归求和 * @param n * @return */ public static double getSquenceSum(int n) { long startTime = System.currentTimeMillis(); if(n == 1) { return 1d; } double sum = 1d; double a = 1d; for(int i = 2; i <= n; i++) { long num = getSquenceValueByRecurvise(i); sum += a / num; } System.out.println("递归求和耗时:" + (System.currentTimeMillis() - startTime) + "ms");//0ms return sum; } /** * 递归方式 * @param n * @return */ public static long getSquenceValueByRecurvise(int n) { if(n == 1) { return 1; } long squenceValue = n * getSquenceValueByRecurvise(n-1); return squenceValue; } /** * 迭代求和 */ public static double getSequenceSumByInterator(int n) { long startTime = System.currentTimeMillis(); if(n == 1) { return 1d; } double sum = 1d; double a = 1d; long beforeSeqValue = 1; long nextSeqValue = 0; for(int i = 2; i <= n; i++ ) { //迭代关系(an = n * a(n-1) an-1 = an;) nextSeqValue = i * beforeSeqValue;//相当于数学中的递推公式 beforeSeqValue = nextSeqValue; sum += a / nextSeqValue; } /*while(n > 1) { nextSeqValue = n * beforeSeqValue; beforeSeqValue = nextSeqValue; n--; }*/ System.out.println("迭代求和耗时:" + (System.currentTimeMillis() - startTime) + "ms");//0ms return sum; } }
阅读全文
0 0
- 求和1+2+3+...N
- 1,2序列求和100
- 1!+2!+...n!求和程序
- 1!+2!+...n!求和程序
- 1!+2!+----+100!阶乘求和
- JavaScript表单求和1
- 1到10求和
- 1到100求和
- 1-20求和
- 循环求和1
- 1到100求和
- 1-100求和数据结构
- 1-100求和
- C9-1 数组求和
- 1040: 数列求和1
- 1-10求和
- [剑指offer]求和1+2+3+....n
- 特殊的求和:1+2+3+...+n
- UVa 754 Treasure Hunt <计算几何(相交判断)>
- Vue 2.0在IE11中打开项目页面空白的问题
- 字符统计/矩阵转置/分数求和
- 浏览器兼容性问题
- oralcle数据库插入当前的时间sql语句
- 求和:1 + 1/2! + 1/3! + 1/4! + 1/5! + ... + 1/50!
- 安装xgboost过程中的一些坑
- 自己动手搭梯子——从vps到SSR菜鸟教程
- 线性支持向量机
- 抽象类&final
- glViewport含义
- Linux系统下top命令详解
- Spark相关问题的故障排除
- 浅谈分布式服务协调技术 Zookeeper