rust prime factorization with struct
Here's an example of how you can implement prime factorization using a struct in Rust:
struct PrimeFactorizer {
num: u64,
}
impl PrimeFactorizer {
fn new(num: u64) -> Self {
PrimeFactorizer { num }
}
fn factorize(&self) -> Vec<u64> {
let mut factors = Vec::new();
let mut num = self.num;
let mut divisor = 2;
while divisor <= num {
if num % divisor == 0 {
factors.push(divisor);
num /= divisor;
} else {
divisor += 1;
}
}
factors
}
}
fn main() {
let factorizer = PrimeFactorizer::new(60);
let factors = factorizer.factorize();
println!("Prime factors: {:?}", factors);
}
In this code, we define a struct called PrimeFactorizer
that holds a single field num
of type u64
, representing the number we want to factorize. We then implement a method new
that allows us to create a new instance of PrimeFactorizer
and initialize the num
field.
The factorize
method is where the prime factorization logic is implemented. It initializes an empty vector factors
to store the prime factors. We then iterate from divisor = 2
up to num
, checking if num
is divisible by divisor
. If it is, we add divisor
to the factors
vector and divide num
by divisor
. If it's not divisible, we increment divisor
by 1. This process continues until divisor
is greater than num
.
In the main
function, we create a PrimeFactorizer
instance with the number 60 and call the factorize
method to obtain the prime factors. Finally, we print the prime factors using println!
.
Note: This code assumes that the number provided for factorization is greater than 1. It may not work correctly for numbers less than or equal to 1.