Find the sum of the closed interval [min,max]
An interval refers to a set that contains all the real numbers between two specific real numbers, and may also contain the two real numbers at the same time.
- The closed interval [10,20] means that
{X|10<=X<=20}
it contains 10 and 20 - The open interval (10, 20) means
{X|10<=X<=20}
that 10 and 20 are not included
function sum(min,max){
console.log(new Date().getTime());
var sum=0, flag=(max-min)%2;
if(flag){
//点集个数为双数
sum=(max-min+1)*((max+min)/2)
}else{
//点集个数为单数
sum=(max+min)*((max-min+1)/2)
}
console.log(new Date().getTime());
return sum
}
console.log(sum(0,101000))
function sum1(min,max){
console.log(new Date().getTime());
var arr=[],sum=0;
for(let i=min;i<=max;i++){
arr.push(i)
}
sum=eval(arr.join('+'))
console.log(new Date().getTime());
return sum
}
console.log(sum1(0,101000))