Last active
August 29, 2015 14:05
-
-
Save mmstick/a0a39289dc5aad645d61 to your computer and use it in GitHub Desktop.
Experimenting with programming in Rust -- My first Rust program.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::os::{args}; | |
use std::io::{stdin}; | |
use std::u64::{parse_bytes}; | |
// Convert the input string into a number if possible | |
fn str_to_number(input: &str) -> u64 | |
{ | |
match parse_bytes(input.as_bytes(), 10) { | |
Some(x) => x, | |
None => 0u64 | |
} | |
} | |
struct FactorList | |
{ | |
number: u64, | |
factors: Vec<u64>, | |
} | |
impl FactorList | |
{ | |
// Creates a new FactorList from a given number. | |
fn origin(input: u64) -> FactorList | |
{ | |
let mut list = FactorList{number: input, factors: Vec::new()}; | |
list.get_factors(); | |
return list; | |
} | |
// Generates a vector of factors from the input argument. | |
fn get_factors(&mut self) | |
{ | |
let mut number = self.number; | |
let mut index = 2; | |
while index <= number { | |
if number % index == 0 { | |
self.factors.push(index); | |
number /= index; | |
index = 2; | |
} | |
index += 1 | |
} | |
} | |
// Print all prime factors of a number. | |
fn print_factors(self) | |
{ | |
print!("{}:", self.number); | |
for factor in self.factors.iter() { | |
print!(" {}", factor); | |
} | |
println!(""); | |
} | |
} | |
// Print factors of all numbers given to stdin if no argument is given. | |
fn stdin_loop() | |
{ | |
for line in stdin().lines() { | |
let number = str_to_number(line.unwrap().as_slice()); | |
FactorList::origin(number).print_factors() | |
} | |
} | |
// Print factors of all numbers given as an argument. | |
fn argument_loop(args: Vec<String>) | |
{ | |
for index in args.slice(1,args.len()).iter() { | |
let number = str_to_number(index.as_slice()); | |
FactorList::origin(number).print_factors() | |
} | |
} | |
fn main() | |
{ | |
let args = args(); | |
if args.len() == 1 { stdin_loop(); } else { argument_loop(args); } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment