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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

How to find all sequences of consecutive prime numbers whose sum equals N in Rust

1 Answer

0 votes
use std::f64;

/*
    Check whether a number is prime.
    Uses a √n loop and skips even numbers after 2.
*/
fn is_prime(value: u32) -> bool {
    if value < 2 {
        return false;
    }
    if value == 2 {
        return true;
    }
    if value % 2 == 0 {
        return false;
    }

    let limit = (value as f64).sqrt() as u32;
    let mut d = 3;

    while d <= limit {
        if value % d == 0 {
            return false;
        }
        d += 2;
    }

    true
}

/*
    Generate all primes up to N.
    Any consecutive prime sum equal to N cannot contain primes larger than N.
*/
fn generate_primes(max_n: u32) -> Vec<u32> {
    let mut primes = Vec::new();
    for n in 2..=max_n {
        if is_prime(n) {
            primes.push(n);
        }
    }
    primes
}

/*
    Find all consecutive prime sequences whose sum equals N.
    Uses a sliding window:
    - Expand the window by moving the right pointer
    - Shrink the window by moving the left pointer
*/
fn find_prime_consecutive_sums(n: u32) {
    let primes = generate_primes(n);

    let mut start: usize = 0;
    let mut end: usize = 0;
    let mut sum: u32 = 0;

    loop {
        if sum < n {
            if end == primes.len() {
                break;
            }
            sum += primes[end];
            end += 1;
        } else if sum > n {
            sum -= primes[start];
            start += 1;
        } else {
            // Found a valid sequence
            print!("Sequence: ");
            for p in &primes[start..end] {
                print!("{} ", p);
            }
            println!();

            // Continue searching
            sum -= primes[start];
            start += 1;
        }
    }
}

/*
    main
*/
fn main() {
    let n: u32 = 41;
    
    println!("Consecutive prime sequences whose sum equals {}:", n);
    find_prime_consecutive_sums(n);
}



/*
run:

Consecutive prime sequences whose sum equals 41:
Sequence: 2 3 5 7 11 13 
Sequence: 11 13 17 
Sequence: 41 

*/

 



answered 5 days ago by avibootz

Related questions

...