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,845 questions

51,766 answers

573 users

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

1 Answer

0 votes
function is_prime(n: number) {
    if (n == 2) {
        return true;
    }
    if (n < 2 || n % 2 == 0) {
        return false;
    }
    for (let i = 3; i * i <= n; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}
    
function cyclically_rotate_left(n: any) {
    let m: any = n;
    let p: number = 1;
    
    while (m >= 10) {
        p *= 10;
        m /= 10;
    }
    
    return parseInt((m + 10 * (n % p)));
}
    
function is_circular_prime(n: number) {
    if (!is_prime(n)) {
        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 = prime
// 3119 = prime
// 9311 = prime
// 1931 = prime

let n: number = 2;
 
for (let i = 0; i < 18; n++) {
    if (is_circular_prime(n)) {
        console.log(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
...