JSFiddle - React, Tailwind, and code Playground
HTML
<div id="input" style="display: none;">
<h3>Input</h3>
<p>Digit to extract: <input id="digit"></p>
<h3>Results</h3>
<p id="results"></p>
</div>
<h3>Log</h3>
<pre id="log"></pre>
JavaScript
/**
* Extract a digit from a Mersenne prime.
*/
// Set up an array of known Mersenne primes.
const primes = [
{ n: 35, p: 110503 },
{ n: 36, p: 132049 },
{ n: 37, p: 216091 },
{ n: 38, p: 756839 },
{ n: 39, p: 859433 },
];
// Log helper.
function log(text, noBreak) {
$('#log').append(noBreak ? text : `${text}<br>`);
}
// Show the input section when we are ready.
function complete() {
$('#input').show();
}
// Populate the array using BigInt (browser dependent).
function fetchPrimes(index) {
if (index > primes.length - 1) {
return complete();
}
const prime = primes[index];
log(`Mersenne prime ${prime.n} `, true);
prime.value = 2n ** BigInt(prime.p) - 1n;
// Also store a base 10 string representation.
prime.stringValue = prime.value.toString(10);
const len = prime.stringValue.length;
log(`has ${len}`
+ ` decimal digits ${prime.stringValue.substring(0, 5)}`
+ `…${prime.stringValue.substring(len - 5)}.`
);
// Wait for a tick to render log.
setTimeout(() => {
fetchPrimes(index + 1);
}, 0);
}
// Bind a function to extract the n'th digit to the input.
$('#digit').on('change', (ev) => {
const n = ev.target.value;
$('#results').html(`Decimal digit number ${n} of…<ul></ul>`);
primes.forEach((prime) => {
const d = prime.stringValue[n - 1];
$('#results ul').append(
`<li>Mersenne prime ${prime.n} `
+ `(2^${prime.p} - 1) `
+ `is ${d}.</li>`
);
});
});
// Start.
fetchPrimes(0);