Skip to content

Instantly share code, notes, and snippets.

@kugimiya
Last active June 26, 2022 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kugimiya/a34ecc52359963dab18d43dee3bb7282 to your computer and use it in GitHub Desktop.
Save kugimiya/a34ecc52359963dab18d43dee3bb7282 to your computer and use it in GitHub Desktop.
Вычислятор чисел Капрекара, считает квадратичные числа (n=2)
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
if (isMainThread) {
console.log(`Число|Сумма строкой|Квадрат числа|Поток #|Время вычисления в своём потоке (мс)|Время работы потока (мс)`);
const threadsCount = +process.argv[2] || 2;
const threads = new Set();
for (let i = 0; i < threadsCount; i++) {
threads.add(new Worker(__filename, { workerData: { start: i + 1, step: threadsCount, threadId: i }}));
}
for (let worker of threads) {
worker.on('error', (err) => { throw err; });
worker.on('exit', () => {
threads.delete(worker);
// console.log(`Thread exiting, ${threads.size} running...`);
});
worker.on('message', (msg) => console.log(msg));
}
} else {
const { start, step, threadId } = workerData;
let i = BigInt(start);
let calcTime = Date.now();
const startTime = Date.now();
const printFunc = (o, f, s, sq, ct) => {
parentPort.postMessage(`${o}|${f}+${s}|${sq}|${threadId}|${Date.now() - ct}|${Date.now() - startTime}`);
calcTime = Date.now();
}
while (true) {
const square = i * i;
const s = square.toString();
const [fp, sp] = [s.slice(0, Math.floor(s.length / 2)), s.slice(Math.floor(s.length / 2), s.length)];
if (i === BigInt(fp) + BigInt(sp)) {
printFunc(i, fp, sp, square, calcTime);
} else {
const [fp1, sp1] = [s.slice(0, Math.ceil(s.length / 2)), s.slice(Math.ceil(s.length / 2), s.length)];
if (i === BigInt(fp1) + BigInt(sp1)) {
printFunc(i, fp1, sp1, square, calcTime);
}
}
i += BigInt(step);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment