I started writing Rust by doing a simple program that will print all prime numbers until it reaches the upper bound that is provided through standard input. Here is my code
use std::io;
fn main() {
println!("Enter a number: ");
let mut limit = String::new();
io::stdin().read_line(&mut limit).expect("failed to read line");
let limit: u64 = limit.trim().parse().expect("Please enter a number.");
if limit <= 0 {
println!("Number must be greater than or equal to 0.");
} else {
let mut is_prime = 0;
for n in 2..limit+1 {
if n < 4 {
is_prime = 1;
}
if n % 2 == 0 && n != 2 {
continue;
}
if n % 3 == 0 && n != 3 {
continue;
}
is_prime = 1;
let mut m = 5;
while m <= (n as f64).sqrt() as u64 {
if n % m == 0 {
is_prime = 0;
break;
}
if n % (m + 2) == 0 {
is_prime = 0;
break;
}
m += 6;
}
if is_prime == 1 {
println!("{}", n);
}
}
}
}
While the program does compile and run without any issues, there are two warnings that come up when I compile. This isn't the biggest concern of my program, but is merely just worth mentioning.
$ rustc primes.rs
primes.rs:11:13: 11:25 warning: value assigned to `is_prime` is never read, #[warn(unused_assignments)] on by default
primes.rs:11 let mut is_prime = 0;
^~~~~~~~~~~~
primes.rs:14:17: 14:25 warning: value assigned to `is_prime` is never read, #[warn(unused_assignments)] on by default
primes.rs:14 is_prime = 1;
^~~~~~~~