use std::thread; use std::sync::{Arc, Mutex}; const MAX : usize = 10000000; static mut primes : Vec = Vec::new(); fn prime_thread(_id : i32, nextnum : Arc>, pcount : Arc>) { let mut num : u64; let mut idx : usize; unsafe { while *pcount.lock().unwrap() < MAX { { let mut lnextnum = nextnum.lock().unwrap(); num = *lnextnum; *lnextnum += 2; } let mut prime : bool = true; idx = 0; let pcount_cval = *pcount.lock().unwrap(); while idx < pcount_cval { let pidx_value : u64 = primes[idx]; if pidx_value * pidx_value <= num { if 0 == (num % pidx_value) { prime = false; break; } idx += 1; } else { break; } } if prime { let mut lpcount = pcount.lock().unwrap(); if *lpcount < MAX { primes.push(num); *lpcount += 1; } else { if primes[*lpcount - 1] > num { primes[*lpcount - 1] = num; } return; } let mut i = *lpcount - 1; while i > 1 { if primes[i-1] > primes[i] { let t = primes[i-1]; primes[i-1] = primes[i]; primes[i] = t; } else { break; } i -= 1; } } } } } fn main() { let threads = 16; unsafe { primes = Vec::with_capacity(MAX); primes.push(2); } let pcount = Arc::new(Mutex::new(1)); let nextnum = Arc::new(Mutex::new(3)); let mut handles = vec![]; for id in 0..threads { let pcount_clone = Arc::clone(&pcount); let nextnum_clone = Arc::clone(&nextnum); let handle = thread::spawn(move || {prime_thread(id, nextnum_clone, pcount_clone)}); handles.push(handle); } for handle in handles { handle.join().unwrap(); } unsafe { let pc = *pcount.lock().unwrap(); /* for n in primes { println!("{n}"); } */ println!("Middle 25 primes:"); for i in pc/2 .. pc/2+25 { print!("{} ", primes[i]); } println!(""); println!("Last 25 primes:"); for i in pc-25 .. pc { print!("{} ", primes[i]); } println!(""); println!("Final pcount: {}\n", pc); /* for i in 0 .. pc - 1 { if primes[i] == primes[i + 1] { println!("Error: Duplicate prime recorded at index {i} and {}", i+1); } } for i in 0 .. pc - 1 { if primes[i] == primes[i + 1] { println!("Note: Out of order primes {} and {}", primes[i], primes[i+1]); } } let check_prime = |num : u64| -> bool { for i in 0 .. pc { if primes[i] > num { return true; } if 0 == num % primes[i] && num != primes[i] { return false; } } return true; }; for i in 0 .. pc { if !check_prime(primes[i]) { println!("Error: {} is not prime!", primes[i]); } } println!("Done checking list for primality"); let was_found = |num : u64| -> bool { for i in 0 .. pc { if primes[i] == num { return true; } } false }; let mut testval : u64 = 2; let mut cc : usize = 0; while cc < MAX && primes[MAX - 1] > testval { if check_prime(testval) { cc += 1; if !was_found(testval) { println!("Error: {testval} is prime but was not found"); } } testval += 1; } */ } }