How to check if a number is circular prime (cyclically rotate left will also be prime) in JavaScript

1 Answer

0 votes
function is_prime(n) {
    if (n == 2) {
        return true;
    }
    if (n < 2 || n % 2 == 0) {
        return false;
    }
    
    const limit = Math.sqrt(n);
    for (let i = 3; i * i <= limit; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }

    return true;
}
     
function cyclically_rotate_left(n) {
    let m = n;
    let p = 1;
     
    while (m >= 10) {
        p *= 10;
        m /= 10;
    }
     
    return parseInt((m + 10 * (n % p)));
}
     
function is_circular_prime(n) {
    if (!Number.isInteger(n) || n < 2) return false;
     
    let rotated_n = cyclically_rotate_left(n);
     
    while (rotated_n != n) {
        if (rotated_n < n || !is_prime(rotated_n)) {
            return false;
        }
        rotated_n = cyclically_rotate_left(rotated_n);
    }
     
    return true;
}

// 1193
// 1193 = prime
// 3119 = prime
// 9311 = prime
// 1931 = prime

const testNumbers = [197, 1193, 23, 101, 119];

for (const n of testNumbers) {
    console.log(`${n} → ${is_circular_prime(n) ? "Circular Prime" : "Not Circular Prime"}`);
}

 
 
/*
run:
 
197 → Circular Prime
1193 → Circular Prime
23 → Not Circular Prime
101 → Not Circular Prime
119 → Circular Prime
 
*/

 



answered Mar 24, 2023 by avibootz
edited Nov 10, 2025 by avibootz
...