Add primes program

master
trivernis 4 years ago
parent 6102d6ea7b
commit 598fd83190

4
.gitignore vendored

@ -0,0 +1,4 @@
/target
**/*.rs.bk
primes.txt
*.tar.gz

35
Cargo.lock generated

@ -0,0 +1,35 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "hermit-abi"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "libc"
version = "0.2.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "num_cpus"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "primes"
version = "0.1.0"
dependencies = [
"num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[metadata]
"checksum hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eff2656d88f158ce120947499e971d743c05dbcbed62e5bd2f38f1698bbc3772"
"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558"
"checksum num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6"

@ -0,0 +1,10 @@
[package]
name = "primes"
version = "0.1.0"
authors = ["trivernis <trivernis@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
num_cpus = "1.0"

@ -0,0 +1,61 @@
extern crate num_cpus;
use std::thread;
use std::fs::{OpenOptions};
use std::io::prelude::*;
use std::sync::mpsc::{sync_channel, SyncSender};
use std::env;
fn main() {
let (tx, rx) = sync_channel::<u64>(0);
let num_threads: u64 = num_cpus::get() as u64;
let mut start: u64 = 1;
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
start = *(&args[1].parse::<u64>().unwrap());
}
if &start % 2 == 0 {
start += 1;
}
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open("primes.txt")
.unwrap();
println!("Starting {} threads", num_threads);
for i in 0u64..num_threads {
let tx = tx.clone();
let _child = thread::spawn(move || {
get_primes(&start + (2*&i), &num_threads * 2, &tx);
});
}
loop {
let prime = rx.recv().unwrap();
println!("{}", prime);
if let Err(e) = writeln!(file, "{}", prime) {
panic!(e);
}
}
}
fn get_primes(start: u64, incr: u64, tx: &SyncSender<u64>) {
let mut num = start;
loop {
let mut is_prime = true;
if (num < 3) | (&num % 2 == 0) {
num += incr;
continue;
}
for i in (3u64..&num/2).step_by(2) {
if &num % i == 0 {
is_prime = false;
}
}
if is_prime {
if let Err(e) = (*tx).send(num) {
panic!(e);
}
}
num += incr;
}
}
Loading…
Cancel
Save