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 check if a number is circular prime (cyclically rotate left will also be prime) in Rust

1 Answer

0 votes
fn is_prime(n : i32) -> bool {
    if n == 2 {
        return true;
    }
    
    if n < 2 || n % 2 == 0 {
        return false;
    }
    
    {
        let mut i : i32 = 3;
        while i * i <= n {
            if n % i == 0 {
                    return false;
                }
                i += 2 as i32;
            }
        }
        return true;
    }
    
fn cyclically_rotate_left(n : i32) -> i32 {
    let mut m : i32 = n;
    let mut p : i32 = 1;
    
    while m >= 10 {
        p *= 10 as i32;
        m /= 10 as i32;
    }
    
    return (m + 10 * (n % p)) as i32;
}
    
fn is_circular_prime(n : i32) -> bool {
    if !is_prime(n) {
        return false;
    }
    
    let mut rotated_n : i32 = 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;
}
    
fn main() {
    print!("{}", is_circular_prime(3779));
}




/*
run:

true

*/

 



answered Mar 24, 2023 by avibootz
...