i need more efficient way increment value 0.0001 every 1 in parsed number. code quoted below won't cause browser crash if enter large number.
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));
update: need ret , base returned
after analysis, function can reduced this:
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));
why?
base = 1 ret = 0 for(var i=1; i<=amm; i++) { base += 0.0001; ret += base; } now, above just: base = 1 + amm*0.0001 // sums 0.0001 amm times , has 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)
some tests:
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));
Comments
Post a Comment