[Solved] Write palindrome in JavaScript [closed]


Just for kicks,

if you’re looking for an answer, it’s 30109 * 33211 = 999949999

if you’re looking for an excessively long, slow and generally unoptimized program, here you go:

function prime(n) {
    if (n < 2 || n == 4) return false;
    if (n < 4) return true;
    for (j = 2; j <= Math.sqrt(n); j++) {
        if (n % j == 0) return false;
    }
    return true;
}
function palindrome(n) {
    n = String(n);
    return n == n.split('').reverse().join('');
}
function f(n) {
    primes = [];
    for (i = Math.pow(10, n-1); i < Math.pow(10, n) - 1; i++)
        if (prime(i)) primes.push(i);
    console.log(primes.length, 'primes found');
    primes.reverse();
    p = a = b = 0;
    for (i = 0; i < primes.length; i++) {
        // if (i % 100 == 0) console.log(i); // prints a sort of progress (gets faster over time)
        for (j = i; j < primes.length; j++) {
            c = primes[i];
            d = primes[j];
            k = c * d;
            if (k < p) break;
            if (palindrome(k)) {
                // console.log('new: ', k); // prints when a new, largest palindrome is found
                p = k;
                a = c;
                b = d;
            }
        }
    }
    return [b, a];
}

result = f(prompt('Size of the primes (careful if >4):'));
console.log(result[0], ' * ', result[1], ' = ', result[0] * result[1]);

solved Write palindrome in JavaScript [closed]