假设我在这里有这个等式:a * (1 - r ^ n) / (1 - r)基本上,它是几何数列之和的公式。在我们的例子中,r是一个小数(浮点数)。我期望得到的数字大于最大安全整数,因此必须使用 BigInt。几何和是否有 BigInt 实现?提前致谢!这是我尝试过的:function geoSum(a, r, n) {
return BigInt(a * ((1 - r ** n) / (1 - n)));
}Infinity在它可以转换为 BigInt 之前,它已经变成了。提前致谢!
2 回答

互换的青春
TA贡献1797条经验 获得超6个赞
您应该在应用操作BigInt 之前将每个参数转换为:
function geoSum(a, r, n) {
const an = BigInt(a);
const rn = BigInt(r);
const nn = BigInt(n);
return an * ((1n - rn ** nn) / (1n - nn));
}
const result = geoSum(150, 151, 152);
console.log(String(result));
console.log(Number(result));

翻过高山走不出你
TA贡献1875条经验 获得超3个赞
我只是用BigInt.
function geoSum(a, r, n) {
return BigInt(BigInt(a) * (BigInt(BigInt(1) - BigInt(BigInt(r) ** BigInt(n))) /
BigInt(BigInt(1) - BigInt(n))));
}
geoSum(2,5,10)
回来:
2170138n
我不知道结果对你是否有意义。
添加回答
举报
0/150
提交
取消