How to find A and B where A and B are prime numbers and A * B = 12349 in Rust

1 Answer

0 votes
use std::f64;

// Function to check if a number is prime
fn is_prime(n: i32) -> bool {
    if n <= 1 {
        return false;
    }
    if n <= 3 {
        return true;
    }
    if n % 2 == 0 || n % 3 == 0 {
        return false;
    }

    let limit: i32 = (n as f64).sqrt() as i32;
    let mut i: i32 = 5;

    while i <= limit {
        if n % i == 0 || n % (i + 2) == 0 {
            return false;
        }
        i += 6;
    }

    return true;
}

// Helper class to return A and B together
struct Pair {
    a: i32,
    b: i32,
}

// Function to find the two prime factors A and B
fn find_ab(n: i32) -> Pair {
    let limit: i32 = (n as f64).sqrt() as i32;

    for i in 2..=limit {
        if n % i == 0 {
            let j: i32 = n / i;
            if is_prime(i) && is_prime(j) {
                return Pair { a: i, b: j };
            }
        }
    }

    return Pair { a: -1, b: -1 }; // No prime factors found
}

fn main() {
    let n: i32 = 12349;

    let result: Pair = find_ab(n);

    if result.a != -1 {
        println!("A = {}, B = {}", result.a, result.b);
    } else {
        println!("Not found.");
    }
}



/*
run:

A = 53, B = 233

*/

 



answered 11 hours ago by avibootz

Related questions

...