Reputation: 15236
How can I debug this with rust-0.10? It works for smaller numbers like 13195... I think I'm hitting some limit with uint
use std::vec;
use std::num;
use std::iter;
fn int_sqrt(n: uint) -> uint {
num::sqrt(n as f64) as uint
}
fn simple_sieve(limit: uint) -> ~[uint] {
if limit < 2 {
return ~[];
}
let mut primes = vec::from_elem(limit + 1, true);
for prime in iter::range_inclusive(2, int_sqrt(limit) + 1) {
if primes[prime] {
for multiple in iter::range_step(prime * prime, limit + 1, prime) {
primes[multiple] = false
}
}
}
iter::range_inclusive(2, limit).filter(|&n| primes[n]).collect()
}
fn main() {
let limit: uint = 600851475143;
let limithalf: uint = limit/2 as uint;
let primes = simple_sieve(limithalf);
let sieved: ~[uint] = primes.move_iter().filter(|&n| limit % n == 0).collect();
println!("{:?}", sieved);
let mut max = 0;
let f = |x: uint| if x > max { max = x };
for x in sieved.iter() {
f(*x);
}
println!("{}", max);
}
Upvotes: 0
Views: 1879
Reputation: 102096
The problem is the huge allocation(s) you're trying to do: the vec::from_elem
call in simple_sieve
is trying to allocate 600851475143/2
bytes, i.e. approximately 280 GB. The allocation is failing (i.e. malloc
returns NULL) which ATM just causes Rust to abort.
This simpler program indicates the problem:
extern crate libc;
fn main() {
let n = 600851475143 / 2;
let p = unsafe {libc::malloc(n as libc::size_t)};
println!("alloc {}", p)
}
prints alloc 0x0
for me. Try using smaller numbers. :)
Upvotes: 2