diff --git a/src/candidate.rs b/src/candidate.rs new file mode 100644 index 0000000..e9598e6 --- /dev/null +++ b/src/candidate.rs @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2025 Nicolás Ortega Froysa + * Author: Nicolás Ortega Froysa + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +pub struct CandidateGenerator { + base:u64, + first_use:bool, +} + +impl CandidateGenerator { + pub fn new() -> CandidateGenerator { + CandidateGenerator { + base: 0, + first_use: true, + } + } + + pub fn next(&mut self) -> u64 { + /* + * All primes, except 2 and 3, will be equal to (n * 6 ± 1). This avoids + * multiples of three, optimizing our counting. + */ + let val; + + if self.base != 0 { + if self.first_use { + val = self.base - 1; + } else { + val = self.base + 1; + } + } else { + if self.first_use { + val = 2; + } else { + val = 3; + } + } + + if self.first_use { + self.first_use = false; + } else { + self.first_use = true; + self.base += 6; + } + + val + } +} diff --git a/src/main.rs b/src/main.rs index 23e57f7..5fd36c3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,6 +25,8 @@ use std::process; use std::rc::Rc; use structopt::StructOpt; +mod candidate; +use candidate::CandidateGenerator; mod worker; #[derive(StructOpt)] @@ -76,5 +78,10 @@ fn main() { let res = *primes_list.borrow().get(opts.num as usize).unwrap(); println!("{}", res); } else { + let mut cand_gen = CandidateGenerator::new(); + + while primes_list.borrow().len() < opts.num as usize { + let cand = cand_gen.next(); + } } }