Created
August 23, 2020 18:09
-
-
Save andrewmatte/6fb5ea40138f64533bc2327d7a19b243 to your computer and use it in GitHub Desktop.
toy program to calculate and cache prime numbers, limited by sqlite3 integer types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//[dependencies] | |
//rusqlite = "0.24.0" | |
use std::env; | |
use rusqlite::{params, Connection}; | |
use std::process; | |
struct Prime { | |
id: i64, | |
} | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
match args.len() { | |
1 => {println!("This program tells you whether a number is prime by checking all factors up to the square root of your number. Trying calling it with a number.")}, | |
2 => { | |
let arg = &args[1]; | |
let number: i64 = match arg.parse() { | |
Ok(n) => { | |
n | |
}, | |
Err(_) => { | |
eprintln!("This number is not an integer"); | |
return; | |
}, | |
}; | |
run(number) | |
}, | |
_ => { | |
// show a help message | |
println!("Send just one number please"); | |
} | |
} | |
} | |
fn run(number: i64) { | |
let conn = Connection::open("./database").unwrap(); | |
conn.execute( | |
"CREATE TABLE IF NOT EXISTS primes (id UNSIGNED BIG INT);", params![], | |
).unwrap(); | |
let mut stmt = conn.prepare("SELECT id FROM primes;").unwrap(); | |
let mut primes: Vec<i64> = vec![]; | |
let prime_iter = stmt.query_map(params![], |row| { | |
Ok(Prime { | |
id: row.get(0)?, | |
}) | |
}).unwrap(); | |
for item in prime_iter { | |
primes.push(item.unwrap().id); | |
} | |
if primes.len() < 2 { | |
primes.push(2); | |
primes.push(3); | |
} | |
let mut guess: i64 = primes[primes.len() - 1]; | |
let original_max = guess; | |
let stopper = (number as f64).sqrt() as i64; | |
while stopper >= guess { | |
if is_prime(guess, &primes, false) { | |
primes.push(guess); | |
} | |
guess += 2; | |
} | |
if is_prime(number, &primes, true) { | |
println!("{} is prime ", number); | |
} else { | |
println!("{} is not prime", number); | |
} | |
println!("saving primes"); | |
for prime in primes { | |
if prime > original_max { | |
conn.execute( | |
"INSERT INTO primes (id) VALUES (?1)", | |
params![prime], | |
).unwrap(); | |
} | |
} | |
process::exit(0); | |
} | |
fn is_prime(num: i64, primes: &Vec<i64>, factor: bool) -> bool { | |
let mut i = 0; | |
let ceiling = (num as f64).sqrt() as i64; | |
while i < primes.len() && primes[i] <= ceiling { | |
if num % primes[i] == 0 { | |
if factor { | |
println!("{} and {}", primes[i], num/primes[i]); | |
} | |
return false; | |
} | |
i += 1; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment