Hey guys, I have a loop that pushes the factors of a number into an array/vector. Here’s the code in Rust:
fn main() {
let mut v: Vec<i32> = Vec::new();
while i <= num {
i += 1;
if num % i == 0 {
v.push(i);
};
}
println!("{}", v)
}
For those who don’t understand rust, here’s a Javascript simulacrum;
let v = [];
for(let i = 1; i <= num; i++) {
if(num % i == 0) {
v.push(i);
}
}
In pseudocode:
- Declare a number.
- Begin looping through every whole positive number before this number
- If the loop number and the original number are divisible with no remainder, push it to a vector/array.
Now, this isn’t optimal - the resultant collection v is being manipulated. If I wanted to convert this into functional code, how would I avoid repeatedly changing v? This is one thing I considered:
- If the number has a remainder of 0:
-
- Make a vector out of the number
-
- When another factor is found, make a vector out of the new number and the elements of the old vector
Any thoughts? I’m relatively new to nonmutable/functional programming and thought this would be a nice way to get into it.