Home  >  Article  >  Web Front-end  >  How to find the cumulative sum of two numbers in JavaScript

How to find the cumulative sum of two numbers in JavaScript

王林
王林Original
2021-10-25 15:05:393550browse

JavaScript method to find the cumulative sum of two numbers: [const method2 = (start: number, end: number) => {return ((end - start 1) * (start end)) /2 }].

How to find the cumulative sum of two numbers in JavaScript

#The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.

Calculate the cumulative sum of two positive integers

The specific code is as follows:

/**
 * @description for循环
 * @param start 开始
 * @param end 结束
 */
const method1 = (start: number, end: number) => {
  // 如果start大于end直接return
  if (start > end) {
    return;
  }
  let sum = 0;
  for (let i = start; i <= end; i++) {
    sum += i;
  }
  return sum;
};
/**
 * @description 高斯算法 公式 项数(首项 + 末项) / 2
 * @param start
 * @param end
 */
const method2 = (start: number, end: number) => {
  return ((end - start + 1) * (start + end)) / 2;
};
 
/**
 * @description 递归算法
 * @param start 
 * @param end 
 */
const method3 = (start: number, end: number) => {
  if (start > end) {
    return;
  } else {
    if (end > start) {
      return end + method3(start, end - 1);
    } else {
      return start
    }
  }
};
 
console.log(method1(8, 100)); // 5022
console.log(method3(8, 100)); // 5022
console.log(method2(8, 100)); // 5022

Recommended learning: javascript video tutorial

The above is the detailed content of How to find the cumulative sum of two numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn