Wrote program for Day 6
This commit is contained in:
parent
9b06185114
commit
2027871010
6
Week-01/Day-06_Next-Prime/next_prime/Cargo.toml
Normal file
6
Week-01/Day-06_Next-Prime/next_prime/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "next_prime"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
16
Week-01/Day-06_Next-Prime/next_prime/src/lib.rs
Normal file
16
Week-01/Day-06_Next-Prime/next_prime/src/lib.rs
Normal 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
|
||||||
|
}
|
23
Week-01/Day-06_Next-Prime/next_prime/src/main.rs
Normal file
23
Week-01/Day-06_Next-Prime/next_prime/src/main.rs
Normal 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"),
|
||||||
|
}
|
||||||
|
}
|
16
Week-01/Day-06_Next-Prime/next_prime/tests/exaples.rs
Normal file
16
Week-01/Day-06_Next-Prime/next_prime/tests/exaples.rs
Normal 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));
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user