gpt4 book ai didi

javascript - 按顺序生成数字

转载 作者:行者123 更新时间:2023-12-01 11:11:25 24 4
gpt4 key购买 nike

我想根据支票中输入的位置生成正在搜索的值。例如输入20,函数应该从0开始生成数字,按照升序排列,直到生成20位,然后输出生成的数字串(01234567891011121314)中第20位的值,即4。我在下面尝试了这个,但是当涉及到像 1,000,000,000 这样的数字时,它效率不高,

[...Array(5).keys()];  output => [0, 1, 2, 3, 4]

编辑这篇文章以阐明我正在尝试获得更有效的解决方案。在这里,我试图在不到一秒的时间内获得长数字 (1,000,000,000) 的答案。

我已经有了解决方案,但需要 1 秒以上。

 [...Array(5).keys()].join("")[4]; output => 4

最佳答案

这与 Champernowne constant 几乎相同.

来自 math.stackexchange 的解决方案是:

enter image description here

(不幸的是,Stack Overflow 不支持 MathJax)

The first step is to find what decade you are in. There are 9 digits from the 1 digit numbers, 2⋅90=180 digits from the 2 digit numbers for a total of 189, and generally n⋅9⋅10n−1 from the n digit numbers. Once you have found the decade, you can subtract the digits from the earlier decades. So if you want the 765th digit, the first 189 come from the first and second decades, so we want the 576th digit of the 3 digit numbers. This will come in the ⌈5763⌉=192nd number, which is 291. As 576≡3(mod3), the digit is 1

以编程方式:

const getDigit = (target) => {
let i = 0;
let xDigitNumbers = 1; // eg 1 digit numbers, 2 digit numbers
let digitsSoFar = 1;
while (true) {
const digitsThisDecade = xDigitNumbers * 9 * 10 ** (xDigitNumbers - 1);
if (digitsSoFar + digitsThisDecade > target) {
// Then this is the "decade" in which the target digit is

// digitIndexThisDecade: eg, starting from '100101102', to find the last '1' in '101', digitIndexThisDecade will be 6
const digitIndexThisDecade = target - digitsSoFar;
// numIndexThisDecade: this identifies the index of the number in the decade
// eg, starting from '100101102', this could be index 2 to correspond to 101 (one-indexed)
const numIndexThisDecade = Math.floor(digitIndexThisDecade / xDigitNumbers);
// decadeStartNum: the number right before the decade starts (0, 9, 99, 999)
const decadeStartNum = 10 ** (xDigitNumbers - 1);
// num: the number in which the target index lies, eg 101
const num = decadeStartNum + numIndexThisDecade;
// digitIndexInNum: the digit index in num that the target is
// eg, for 101, targeting the last '1' will come from a digitIndexInNum of 2 (zero-indexed)
const digitIndexInNum = digitIndexThisDecade % xDigitNumbers;
return String(num)[digitIndexInNum]
}
digitsSoFar += digitsThisDecade;
xDigitNumbers++;
}
};



for (let i = 0; i < 1000; i++) {
document.write(`${i}: ${getDigit(i)}<br>`);
}

关于javascript - 按顺序生成数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com