我需要一种更有效的方法,在解析后的数字中每增加一个值0.0001。比如下面引用的代码,但如果输入的数字过大,会导致浏览器崩溃。
function example(amm) {
var base = 1;
var ret = 0;
for(var i=1; i<=amm; i++) {
base += 0.0001;
ret += base;
}
return [base,ret];
};
var total = example(100);
console.log(total[0].toFixed(4));
console.log(total[1].toFixed(4));
&#13;
更新:我需要ret和base返回
答案 0 :(得分:3)
经过一些分析,您的功能可以简化为:
function example(amm) {
var base = 1 + amm*0.0001;
var ret = amm + 0.0001 * (amm)*(amm + 1)/2;
return [base.toFixed(4), ret.toFixed(4)];
}
console.log(example(100));
console.log(example(200));
console.log(example(1000));
console.log(example(2000));
&#13;
为什么?
base = 1
ret = 0
for(var i=1; i<=amm; i++) {
base += 0.0001;
ret += base;
}
now, the above is just:
base = 1 + amm*0.0001 // it sums 0.0001 amm times and has an initial value of 1
ret = 1 + (1.0001) + (2.0002) + (3.0003) + (4.0004) + ... + (amm + 0.0001*amm)
= 1*amm + 0.0001*((amm)*(amm + 1)/2)
= amm + 0.0001*((amm)*(amm + 1)/2)
一些测试:
function example1(amm) {
var base = 1;
var ret = 0;
for(var i=1; i<=amm; i++) {
base += 0.0001;
ret += base;
}
return [base.toFixed(4), ret.toFixed(4)];
}
function example2(amm) {
var base = 1 + amm*0.0001;
var ret = amm + 0.0001 * (amm)*(amm + 1)/2;
return [base.toFixed(4), ret.toFixed(4)];
}
console.log(example1(100) + ' === ' + example2(100));
console.log(example1(1564) + ' === ' + example2(1564));
console.log(example1(21343) + ' === ' + example2(21343));
console.log(example1(132) + ' === ' + example2(132));
console.log(example1(0) + ' === ' + example2(0));
console.log(example1(1) + ' === ' + example2(1));
&#13;
答案 1 :(得分:1)
你有一个序列。
B(n)= B(n-1)+ 0.0001,n> 1
B(0)= 1
S(n)= S(n-1)+ B(n),n> 1
S(1)= 0
B(n)=(0.0001 * n)+ 1
S(n)= S(n-1)+(0.0001 * n)+ 1,n> 1。 1
S(1)= 0
S(n)= 0.0001 * n *(n + 1)/ 2 + n