I'm new to the Rust language, and I've been working on this, my first Rust project, to get a better grasp of how the lang works. I've got this code that calculates primes, but it stops every time it reaches the value 16,777,213. It doesn't panic, it doesn't crash, it just freezes. I've found another post where someone tried a similar thing in C++ and has the same problem: Prime number generator stops abruptly at 16777213 | StackOverflow, but nobody seems to answer how to fix it.
Here is my code:
fn half(val: i128) -> bool { // For better precision (to prevent false positives in small numbers)
let mut factors: Vec<i128> = vec![];
for i in 1i128..(((val as f32)/2.0)+1.0) as i128 {
let factor: f32 = (val as f32)/(i as f32);
if factor == factor.round() {
let factor:i128 = factor as i128;
if factor != val {
factors.push(factor as i128)
}
}
}
if factors.is_empty() {
return true
} else {false}
}
fn root(val:i128) -> bool {
let mut factors: Vec<i128> = vec![];
for i in 1i128..((val as f32).sqrt().round()+1.0) as i128 {
if val > 2 {
let factor: f32 = (val as f32)/(i as f32);
if factor == factor.round() {
let factor: i128 = factor as i128;
if factor != val {
factors.push(factor)
}
}
}
}
if factors.is_empty() {
return true
} else {false}
}
fn is_prime(val:i128) -> bool {
if val > 100 {
root(val)
}
else {
half(val)
}
}
fn main() {
//let mut primes: Vec<i128> = vec![];
let mut i:i128 = 16_700_000;
loop {
let prime: bool = is_prime(i);
if prime {
println!("{}",i)
/*
This was the original code, but I removed the vector so that I'd be able to
determine the exact value at which the script breaks at.
primes.push(i);
if primes.len() as i32 == 24 {
println!("{:?}",primes);
primes.clear()
}*/
}
i += 1
}
}