Wrote program for Day 6

This commit is contained in:
Mariano Riefolo 2024-07-31 21:14:40 +02:00
parent 9b06185114
commit 2027871010
4 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "next_prime"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,16 @@
pub fn next_prime(num: usize) -> Option<usize> {
let max_next_prime = num * 2;
let mut is_prime: Vec<bool> = vec![true; max_next_prime];
for i in 2..max_next_prime {
for j in (i * 2..max_next_prime).step_by(i) {
is_prime[j] = false;
}
if i >= num && is_prime[i] {
return Some(i);
}
}
None
}

View File

@ -0,0 +1,23 @@
use next_prime::next_prime;
use std::io::{self, Write};
fn main() {
let mut buffer = String::new();
print!("Give me an integer, and I will return the first prime found from that: ");
io::stdout().flush().expect("Failed to flush stdout.");
io::stdin()
.read_line(&mut buffer)
.expect("Error while trying to read the number.");
let num: usize = buffer
.trim()
.parse()
.expect("The input inserted is not a valid integer");
match next_prime(num) {
Some(x) => println!("Here's the first prime found from {}: {}", num, x),
None => println!("None found"),
}
}

View File

@ -0,0 +1,16 @@
use next_prime::next_prime;
#[test]
fn first_example() {
assert_eq!(next_prime(12), Some(13));
}
#[test]
fn second_example() {
assert_eq!(next_prime(24), Some(29));
}
#[test]
fn third_example() {
assert_eq!(next_prime(11), Some(11));
}