Created
June 14, 2013 16:38
-
-
Save azdle/5783394 to your computer and use it in GitHub Desktop.
Project Euler Problem 3 in Rust using MutList
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
#!/usr/local/bin/rust run | |
/** | |
The prime factors of 13195 are 5, 7, 13 and 29. | |
What is the largest prime factor of the number 600851475143 ? | |
*/ | |
extern mod extra; | |
use std::*; | |
use extra::list; | |
fn check_prime(number: uint, known_primes: &list::MutList<uint>) -> bool{ //This function borrows the pointer to the list of primes to prevent it being copied. | |
for known_primes.each |&value: &uint| { | |
if number % value == 0{ | |
return false; | |
} | |
} | |
return true; | |
} | |
fn find_primes_to(upper_limit: uint) -> ~list::MutList<uint>{ | |
let mut primes: ~list::MutList<uint>; | |
for uint::range(2, upper_limit) |value| { | |
if check_prime(value, primes){ | |
primes.append(value); | |
//println(fmt!("Prime: %u\r" ,value)); | |
} | |
} | |
return primes; | |
} | |
fn check_is_factor(potential_factor: uint, of: uint) -> bool{ | |
if of % potential_factor == 0{ | |
true | |
}else{ | |
false | |
} | |
} | |
fn main(){ | |
let startnum = 600851475143; | |
let mut largest_result = 0; | |
let primes = find_primes_to(float::sqrt(startnum as float) as uint); | |
for primes.each |prime| { | |
if check_is_factor(*prime, startnum){ | |
if *prime > largest_result{ | |
largest_result = *prime; | |
} | |
} | |
} | |
println(fmt!("The Largest Factor is: %u", largest_result)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment