Unprimeable numbers: Difference between revisions

J
(→‎{{header|REXX}}: optimized the GENP subroutine.)
(J)
Line 1,047:
8 is 208
9 is 212,159
</pre>
 
=={{header|JavaScript}}==
Auxiliary function:
<lang javascript>
Number.prototype.isPrime = function() {
let i = 2, num = this;
if (num == 0 || num == 1) return false;
if (num == 2) return true;
while (i <= Math.ceil(Math.sqrt(num))) {
if (num % i == 0) return false;
i++;
}
return true;
}
</lang>
 
Core function:
<lang javascript>
function isUnprimable(num) {
if (num < 100 || num.isPrime()) return false;
let arr = num.toString().split('');
for (let x = 0; x < arr.length; x++) {
let lft = arr.slice(0, x),
rgt = arr.slice(x + 1);
for (let y = 0; y < 10; y++) {
let test = lft.join('') + y.toString() + rgt.join('');
if (parseInt(test).isPrime()) return false;
}
}
return true;
}
<lang>
 
Main function for output:
<lang javascript>
let unprimeables = [],
endings = new Array(10).fill('-'),
c = 1;
function chkEnds(n) {
let e = n % 10;
if (endings[e] == '-') endings[e] = n;
}
console.time('I');
while (unprimeables.length < 1000) {
if (isUnprimable(c)) {
unprimeables.push(c);
chkEnds(c)
}
c++;
}
console.log('The first 35 unprimeables:');
console.log(unprimeables.slice(0,35).join(', '));
console.log(`The 600th unprimeable: ${unprimeables[599].toLocaleString('en')}`);
console.log(`The 1000th unprimable: ${unprimeables[999].toLocaleString('en')}`);
console.timeEnd('I');
console.time('II');
while (endings.includes('-')) {
c++;
if (isUnprimable(c)) chkEnds(c);
}
for (c = 0; c < endings.length; c++) {
console.log(`First unprimeable ending with ${c}: ${endings[c].toLocaleString('en')}`);
}
console.timeEnd('II');
</lang>
 
{{out}}
<pre>
The first 35 unprimeables:
200, 204, 206, 208, 320, 322, 324, 325, 326, 328, 510, 512, 514, 515, 516, 518, 530, 532, 534, 535, 536, 538, 620, 622, 624, 625, 626, 628, 840, 842, 844, 845, 846, 848, 890
 
The 600th unprimeable: 5,242
The 1000th unprimable: 8,158
I: 240ms - timer ended
 
First unprimeable ending with 0: 200
First unprimeable ending with 1: 595,631
First unprimeable ending with 2: 322
First unprimeable ending with 3: 1,203,623
First unprimeable ending with 4: 204
First unprimeable ending with 5: 325
First unprimeable ending with 6: 206
First unprimeable ending with 7: 872,897
First unprimeable ending with 8: 208
First unprimeable ending with 9: 212,159
II: 186884ms - timer ended
</pre>