Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 23, 2018 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/b5731d7998946734662b9766a6a8ecc7 to your computer and use it in GitHub Desktop.
Save rust-play/b5731d7998946734662b9766a6a8ecc7 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
fn factorize(mut composite: u64) -> Vec<u64> {
let mut factors: Vec<u64> = Vec::new();
while composite % 2 == 0 {
composite /= 2;
factors.push(2);
}
let mut f = 3;
while f * f <= composite {
if composite % f == 0 {
factors.push(f);
composite /= f;
} else {
f += 2;
}
}
if composite != 1 {
factors.push(composite);
}
return factors
}
fn foobar(composite: u64) -> String{
let factors = factorize(composite);
let mut reply: String = "`".to_string();
if factors.len() > 1 {
let mut cur_factor: &u64 = factors.first().unwrap();
let mut times_repeated = 1;
for i in factors.iter().skip(1) {
if i != cur_factor {
if times_repeated != 1 {
reply.push_str(&format!(" {}^{} *", cur_factor, times_repeated));
times_repeated = 1;
} else {
reply.push_str(&format!(" {} *", cur_factor));
}
cur_factor = i;
} else {
times_repeated += 1;
}
}
if composite != 1 {
reply.push_str(&format!(" {}`", composite));
} else {
let len = reply.len() - 2;
reply.truncate(len);
reply.push('`');
}
} else {
reply = format!("`{} is a prime number`",factors.first().unwrap());
}
reply
}
fn main(){
println!("{}", foobar(25))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment