I am getting PI number from PI Api (https://pi.delivery) and checking for palindromic of 21 numbers in sequence on each 105 numbers block (5 x 21) to be faster. My code returns undefined on the second round of for loop. Why is this happening?
PS: This is a 105 numbers block and 2 rounds loop just for testing purpose.
import fetch from "node-fetch";
import fs from "fs";
const contentPI = async (start, size) => {
return await fetch(`https://api.pi.delivery/v1/pi?start=${start}&numberOfDigits=${size}`)
.then(response => response.json())
.then(data => data.content);
}
let start = 1;
let size = 105;
let group = 0;
for (let y = 0; y < 2; y = 1) {
const pi = await contentPI(start, size);
let sequence = '';
for (let i = 0; i < 5; i = 1) {
let count = 0;
for (let j = group; j < group 21; j = 1) {
sequence = pi[j];
}
console.log(sequence, ' - ', i, 'seq');
for (let x = 2; x <= 10; x = 1) {
if (sequence % x === 0) {
count ;
}
}
const result = (count > 0) ? 'not prime' : 'prime';
if (result === 'prime') {
const reverseSequence = sequence.split('').reverse().join('');
if (sequence === reverseSequence) {
console.log(`${sequence} - palindromic prime - position: ${i * 9}`);
}
}
sequence = '';
group = 21;
count = 0;
if (i === 4) {
start = 105;
}
}
}
CodePudding user response:
Pay attention to your group
and for (let j = group...)
. You have for (let i = 0; i < 5; i = 1)
and in the end of this loop you are adding 21
to group
. For first y
loop everything works, but for 2nd y
loop you are not resetting group
back to 0
, so it keeps growing and due to that your j
variable becomes bigger than the length of the pi
variable. So you are starting getting "undefined" then. Probably you need to move let group = 0;
a bit down, into the beginning of the for (let y = 0; y < 2; y = 1)
loop.
const contentPI = async (start, size) => {
return await fetch(
`https://api.pi.delivery/v1/pi?start=${start}&numberOfDigits=${size}`
)
.then((response) => response.json())
.then((data) => data.content);
};
async function doSomething() {
let start = 1;
let size = 105;
for (let y = 0; y < 2; y = 1) {
let group = 0;
const pi = await contentPI(start, size);
console.log(y, pi);
let sequence = "";
for (let i = 0; i < 5; i = 1) {
let count = 0;
for (let j = group; j < group 21; j = 1) {
sequence = pi[j];
}
console.log(sequence, " - ", i, "seq");
for (let x = 2; x <= 10; x = 1) {
if (sequence % x === 0) {
count ;
}
}
const result = count > 0 ? "not prime" : "prime";
if (result === "prime") {
const reverseSequence = sequence.split("").reverse().join("");
if (sequence === reverseSequence) {
console.log(`${sequence} - palindromic prime - position: ${i * 9}`);
}
}
sequence = "";
group = 21;
count = 0;
if (i === 4) {
start = 105;
}
}
}
}
doSomething();