How to find the first 4-digit prime number where all digits are unique in Rust

1 Answer

0 votes
use std::f64;

fn is_prime(n: i32) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }

    let limit = (n as f64).sqrt() as i32;
    let mut i = 3;
    while i <= limit {
        if n % i == 0 {
            return false;
        }
        i += 2;
    }
    
    true
}

fn has_unique_digits(mut n: i32) -> bool {
    let mut seen = [false; 10];

    while n > 0 {
        let d = (n % 10) as usize;
        if seen[d] {
            return false;
        }
        seen[d] = true;
        n /= 10;
    }
    
    true
}

fn main() {
    for num in 1000..=9999 {
        if is_prime(num) && has_unique_digits(num) {
            println!("First 4-digit prime with all unique digits: {}", num);
            return; // stop after finding the first one
        }
    }
    println!("No such number found.");
}




/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered 8 hours ago by avibootz
...