简体   繁体   English

编写一个函数sumRange,当给定两个整数FROM和TO时,该函数返回从FROM到TO的整数之和

[英]Write a function sumRange, which, when given two integers FROM and TO, returns the sum of integers from FROM to TO

Could anyone please tell me how I could write this code better, I'm having a bit of trouble getting mine to work 任何人都可以告诉我如何更好地编写此代码,让我上班有点麻烦

function sumRange(from, to) {
      var f = from;
      var t = to;
      var result = from;
      if(to >= from) {
        while (to > from) {
          from ++;
          result += from;
        }
        return result;
      } else if (from > to) {
        result = to;
        while (from > to ) {
          to++;
          result += to;
        }
        return result;
      }

    }

The sum of the integers between a and b is: ab之间的整数之和为:

((b - a + 1) * (a + b)) / 2

See http://mathworld.wolfram.com/ArithmeticSeries.html 参见http://mathworld.wolfram.com/ArithmeticSeries.html

To handle the arguments in any order: 要以任何顺序处理参数:

function sumRange(a, b) {
    return ((Math.abs(b - a) + 1) * (a + b)) / 2;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从字符串获取整数 - Getting the integers from a string 如何使用递归编写 function,该递归采用 2 个整数并返回包含 2 个输入整数之间的整数的数组 - How to write a function using recursion that takes 2 integers and returns an array containing integers between the 2 input integers JavaScript 递归循环对嵌套数组中的所有整数求和 - JavaScript recursive loop to sum all integers from nested array 给定两个整数的字符串表示形式,返回这些整数之和的字符串表示形式 - Given the string representations of two integers, return the string representation of the sum of those integers 你怎么能给出两个整数a和b,可以是正数也可以是负数,并找到包括它们之间的所有数字的总和并返回它 - how can you Given two integers a and b, which can be positive or negative,and find the sum of all the numbers between including them too and return it 根据条件打印 a 到 b 的整数 - Print integers from a to b with condition 从元素的文本中获取整数 - Getting the integers from text of an element 排序数组中缺少整数 - missing integers from a sorted array 从两个整数生成编码的案卷编号并对其进行解码 - Generate encoded docket number from two integers and decode it Function 确定一系列连续(正)整数是否可以写成两个(正)复合相对素数的总和 - Function to determine if a range of consecutive (positive) integers can be written as the sum of two (positive) composite-relatively prime integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM