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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to calculate all the less than 500 additive prime numbers in Rust

1 Answer

0 votes
// Additive primes: primes whose sum of digits is also prime

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

    let mut i = 5;
    while i * i <= n {
        if n % i == 0 {
            return false;
        }
        i += 2;
        if n % i == 0 {
            return false;
        }
        i += 4;
    }

    true
}

// Compute the sum of digits of a number
fn sum_digits(mut n: u32) -> u32 {
    let mut sum = 0;
    while n > 0 {
        sum += n % 10;
        n /= 10;
    }
    sum
}

// Check if a number is an additive prime
fn is_additive_prime(n: u32) -> bool {
    is_prime(n) && is_prime(sum_digits(n))
}

fn main() {
    const TOP: u32 = 500;
    let mut count = 0;

    for n in 1..TOP {
        if is_additive_prime(n) {
            print!("{:3}", n);
            count += 1;

            if count % 10 == 0 {
                println!();
            } else {
                print!(" ");
            }
        }
    }

    println!("\n");
    println!("Total additive primes = {}", count);
}



/*
run:

  2   3   5   7  11  23  29  41  43  47
 61  67  83  89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487

Total additive primes = 54

*/

 



answered May 4 by avibootz
...