Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to find the first 18 circular prime numbers (cyclically rotate left will also be prime) in PHP

1 Answer

0 votes
function is_prime($n) {
    if ($n == 2) {
        return true;
    }
    if ($n < 2 || $n % 2 == 0) {
        return false;
    }
    for ($i = 3; $i * $i <= $n; $i += 2) {
        if ($n % $i == 0) {
            return false;
        }
    }
    return true;
}

function cyclically_rotate_left($n) {
    $m = $n;
    $p = 1;
    
    while ($m >= 10) {
        $p *= 10;
        $m /= 10;
    }
    return (int)($m + 10 * ($n % $p));
}

function is_circular_prime($n) {
    if (!is_prime($n)) {
        return false;
    }
    
    $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;
}

$n = 2;
for ($i = 0; $i < 18; $n++) {
    if (is_circular_prime($n)) {
        if ($i > 0) {
            echo ", ";
        }
        printf("%d",$n);
        $i++;
    }
}




/*
run:

2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939

*/

 



answered Mar 24, 2023 by avibootz
...