Compare commits
27 Commits
65314d52ac
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 0cc8e94224 | |||
| 1348f4343a | |||
| 83b5e4a561 | |||
| 084aa14026 | |||
| 966574dd1f | |||
| 41bc18a17c | |||
| 5dde94ae8c | |||
| be3fd52cfa | |||
| 0b391ed590 | |||
| f5b971e35f | |||
| abfb1aee89 | |||
| 4b3bf0cfac | |||
| ba3478e6ce | |||
| 5ee76502fa | |||
| 72d6f4e042 | |||
| d4dc54fe59 | |||
| c7f4f3c2c4 | |||
| 6c789195e6 | |||
| 98cb2f58ea | |||
| 073276da10 | |||
| 56a094730c | |||
| 3a4a5c8849 | |||
| c0f3f730ae | |||
| 97d756bab4 | |||
| 91c9eaf1b9 | |||
| 92bb314b55 | |||
| 05e18e5aef |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1,3 @@
|
||||
/target
|
||||
/indivisible.1.gz
|
||||
callgrind.out.*
|
||||
|
||||
41
README.md
41
README.md
@@ -1,38 +1,29 @@
|
||||
# Indivisible
|
||||
|
||||
Indivisible is an optimized prime number generator and tester written in Rust.
|
||||
Indivisible is an optimized prime number generator and tester.
|
||||
|
||||
## Build & Installation
|
||||
|
||||
To build the project you will require the Rust compiler and build
|
||||
system, `cargo`. At which point you simply run `cargo build` in the root
|
||||
directory of the project. To create an optimized release build append
|
||||
the `--release` flag to the previous command.
|
||||
Build a binary release using the following command:
|
||||
|
||||
Once a release build has been compiled, you may install Indivisible and
|
||||
the manpage documentation by running the `install` script. In a similar
|
||||
manner, you can run the `uninstall` script to remove the previously
|
||||
installed binary and documentation.
|
||||
```console
|
||||
$ cargo build -r
|
||||
```
|
||||
|
||||
## Usage
|
||||
Once compiled, you can install it using the `install` script. By default this
|
||||
will install to `/usr/local/{bin,share}`, but you can optionally change the
|
||||
`PREFIX` used as follows:
|
||||
|
||||
The purpose of Indivisible is to find the nth prime and all the primes
|
||||
before it. The basic usage is `indivisible <n>` where `n` is the ordinal
|
||||
of the prime you'd like to find. To display all primes before `n`, you
|
||||
can run verbose mode by using the `--verbose` or simply `-v` option.
|
||||
```console
|
||||
$ PREFIX="~/.local" ./install
|
||||
```
|
||||
|
||||
Since Indivisible generates primes using previously computed primes, you
|
||||
can also import prime numbers previously computed with the `--import` or
|
||||
`-i` option. To store already computed primes you are expected to use
|
||||
piping like any UNIX user would expect. Here is an example:
|
||||
Additionally there is an `uninstall` script available. If you have used a custom
|
||||
`PREFIX` this must also be specified to uninstall in the same manner. To see
|
||||
where you've installed it you can always use the following command:
|
||||
|
||||
```bash
|
||||
# store first 100 primes in ./primes
|
||||
indivisible -v 100 > ./primes
|
||||
# appends next 400 primes
|
||||
indivisible -i ./primes -v 500 >> ./primes
|
||||
# display the 600th prime
|
||||
indivisible -i ./primes 600
|
||||
```console
|
||||
$ which indivisible
|
||||
```
|
||||
|
||||
## Legacy
|
||||
|
||||
45
benchmark.sh
Executable file
45
benchmark.sh
Executable file
@@ -0,0 +1,45 @@
|
||||
#!/bin/bash
|
||||
|
||||
EXE="./target/release/indivisible"
|
||||
OPTIONS=()
|
||||
TRIALS=20
|
||||
|
||||
if ! [ -f "$EXE" ]
|
||||
then
|
||||
>&2 echo "Release build not available. Please run 'cargo build -r'."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v calc &>/dev/null
|
||||
then
|
||||
>&2 echo "Missing 'calc' program. Please install it for this script."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while getopts "t:s:" opt
|
||||
do
|
||||
case "$opt" in
|
||||
s)
|
||||
OPTIONS=("${OPTIONS[@]}" -s "$OPTARG")
|
||||
;;
|
||||
t)
|
||||
TRIALS="$OPTARG"
|
||||
;;
|
||||
*)
|
||||
>&2 echo "Uknown option $opt"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "Calculating primes up to 1,000,000,000"
|
||||
TOTAL="0"
|
||||
for _ in $(seq "$TRIALS")
|
||||
do
|
||||
TIME=$(command time -f "%e" "$EXE" "${OPTIONS[@]}" 1000000000 2>&1 >/dev/null)
|
||||
TOTAL=$(calc "$TOTAL + $TIME")
|
||||
done
|
||||
|
||||
AVG=$(calc "$TOTAL / $TRIALS")
|
||||
|
||||
echo "Average time: ${AVG}s"
|
||||
@@ -6,7 +6,9 @@ indivisible \- prime number generator and tester
|
||||
[\fIOPTIONS\fR] <\fIn\fR>
|
||||
|
||||
.SH "DESCRIPTION"
|
||||
Indivisible is a program for working with prime numbers. Its default behaviour will attempt to find the \fInth\fR prime.
|
||||
Indivisible is a program for working with prime numbers. It can either generate
|
||||
primes up to a limit \fIn\fR or test to see if \fIn\fR is a prime. It makes use
|
||||
of a segmented sieve of Eratosthenes.
|
||||
|
||||
.SH "OPTIONS"
|
||||
.TP
|
||||
@@ -19,6 +21,9 @@ Import prime numbers from \fIFILE\fR
|
||||
\fB\-t\fR, \fB\-\-test\fR
|
||||
Test if n is a prime instead of generation
|
||||
.TP
|
||||
\fB\-s\fR, \fB\-\-sieve\fR <\fISIZE\fR>
|
||||
Set a custom sieve size
|
||||
.TP
|
||||
\fB\-v\fR, \fB\-\-verbose\fR
|
||||
Print all found primes
|
||||
.TP
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2025 Nicolás Ortega Froysa <nicolas@ortegas.org>
|
||||
* Author: Nicolás Ortega Froysa <nicolas@ortegas.org>
|
||||
*
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
pub struct CandidateGenerator {
|
||||
base:u64,
|
||||
// first use of the base
|
||||
first_use:bool,
|
||||
}
|
||||
|
||||
impl CandidateGenerator {
|
||||
pub fn new() -> Self {
|
||||
CandidateGenerator {
|
||||
base: 0,
|
||||
first_use: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calc_base(&mut self, last_prime:u64) {
|
||||
if last_prime == 2 {
|
||||
self.base = 0;
|
||||
self.first_use = false;
|
||||
} else if last_prime == 3 {
|
||||
self.base = 6;
|
||||
self.first_use = true;
|
||||
} else {
|
||||
let modulo = last_prime % 6;
|
||||
if modulo == 1 {
|
||||
self.base = last_prime + 5;
|
||||
self.first_use = true;
|
||||
} else if modulo == 5 {
|
||||
self.base = last_prime + 1;
|
||||
self.first_use = false;
|
||||
} else {
|
||||
panic!("Invalid last prime {}" , last_prime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.base += 6;
|
||||
}
|
||||
self.first_use = !self.first_use;
|
||||
|
||||
val
|
||||
}
|
||||
}
|
||||
100
src/main.rs
100
src/main.rs
@@ -16,15 +16,12 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use structopt::StructOpt;
|
||||
|
||||
mod candidate;
|
||||
use candidate::CandidateGenerator;
|
||||
mod worker;
|
||||
|
||||
#[derive(StructOpt)]
|
||||
@@ -36,81 +33,72 @@ struct Opt {
|
||||
import:Option<PathBuf>,
|
||||
#[structopt(short, long, help = "Test if num is prime instead of generation")]
|
||||
test:bool,
|
||||
#[structopt(help = "Ordinal of the prime to generate or number to test for primality")]
|
||||
num:u64,
|
||||
#[structopt(short, long, name = "n", default_value = "1", help = "Number of threads to spawn")]
|
||||
jobs:u64,
|
||||
#[structopt(help = "Max of the prime to generate or number to test for primality")]
|
||||
num:usize,
|
||||
#[structopt(short, long, name = "SIZE", default_value = "10485760", help = "Set a custom sieve size")]
|
||||
sieve:usize,
|
||||
//#[structopt(short, long, name = "n", default_value = "1", help = "Number of threads to spawn")]
|
||||
//jobs:u64,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let opts = Opt::from_args();
|
||||
|
||||
let mut prime_list = VecDeque::<u64>::new();
|
||||
let mut prime_list = Vec::new();
|
||||
|
||||
if opts.import.is_some() {
|
||||
let in_file = File::open(opts.import.unwrap()).unwrap();
|
||||
let reader = BufReader::new(in_file);
|
||||
for p in reader.lines().into_iter() {
|
||||
prime_list.push_back(p.unwrap().parse().unwrap());
|
||||
let prime:u64 = p.unwrap().parse().unwrap();
|
||||
if (prime as usize) > opts.num {
|
||||
break;
|
||||
}
|
||||
|
||||
prime_list.push(prime);
|
||||
}
|
||||
}
|
||||
|
||||
if opts.num == 0 {
|
||||
if opts.num < 2 {
|
||||
eprintln!("Invalid value for num: {}", opts.num);
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
if opts.test && *prime_list.back().unwrap_or(&0) >= opts.num {
|
||||
for i in prime_list.iter() {
|
||||
if *i == opts.num {
|
||||
process::exit(0)
|
||||
}
|
||||
}
|
||||
process::exit(1)
|
||||
} else if !opts.test && prime_list.len() >= opts.num as usize {
|
||||
let res = *prime_list.get(opts.num as usize).unwrap();
|
||||
println!("{}", res);
|
||||
let mut start:usize = if prime_list.is_empty() {
|
||||
2
|
||||
} else {
|
||||
let mut cand_gen = CandidateGenerator::new();
|
||||
if !prime_list.is_empty() {
|
||||
cand_gen.calc_base(*prime_list.back().unwrap());
|
||||
}
|
||||
(*prime_list.last().unwrap() + 1) as usize
|
||||
};
|
||||
while start < opts.num {
|
||||
let end = if start + opts.sieve < opts.num {
|
||||
start + opts.sieve
|
||||
} else {
|
||||
opts.num + 1
|
||||
};
|
||||
let mut new_primes = worker::work_segment(&prime_list, start, end);
|
||||
|
||||
loop {
|
||||
let cand = cand_gen.next();
|
||||
if opts.test && cand > opts.num {
|
||||
break;
|
||||
}
|
||||
|
||||
let mut is_prime = true;
|
||||
for p in prime_list.iter() {
|
||||
if cand % *p == 0 {
|
||||
is_prime = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if is_prime {
|
||||
prime_list.push_back(cand);
|
||||
if opts.verbose {
|
||||
println!("{}", cand);
|
||||
}
|
||||
|
||||
if !opts.test && prime_list.len() == opts.num as usize {
|
||||
break;
|
||||
}
|
||||
if opts.verbose {
|
||||
for p in &new_primes {
|
||||
println!("{}", *p);
|
||||
}
|
||||
}
|
||||
prime_list.append(&mut new_primes);
|
||||
|
||||
if opts.test {
|
||||
if *prime_list.back().unwrap() == opts.num {
|
||||
process::exit(0)
|
||||
} else {
|
||||
process::exit(1)
|
||||
start += opts.sieve;
|
||||
}
|
||||
|
||||
if opts.test {
|
||||
if *prime_list.last().unwrap() == (opts.num as u64) {
|
||||
if opts.verbose {
|
||||
println!("{} is prime", opts.num);
|
||||
}
|
||||
} else if !opts.verbose {
|
||||
let last_prime = *prime_list.back().unwrap();
|
||||
println!("{}", last_prime);
|
||||
process::exit(0);
|
||||
} else {
|
||||
if opts.verbose {
|
||||
println!("{} is composite", opts.num);
|
||||
}
|
||||
process::exit(1);
|
||||
}
|
||||
} else if !opts.verbose {
|
||||
println!("{}", prime_list.last().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,21 +16,51 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
/**
|
||||
* @brief Work on a segment.
|
||||
*
|
||||
* @param known_primes:&Vec<u64> List of known primes at least until sqrt(end).
|
||||
* @param start:usize Beginning of the segment (inclusive).
|
||||
* @param end:usize End of the segment (exclusive).
|
||||
*
|
||||
* @return List of primes found in segment.
|
||||
*/
|
||||
pub fn work_segment(known_primes:&Vec<u64>, start:usize, end:usize) -> Vec<u64> {
|
||||
let mut sieve = vec![true; end - start];
|
||||
let mut found_primes = Vec::new();
|
||||
|
||||
pub struct Worker {
|
||||
prime_list:Rc<RefCell<VecDeque<u64>>>,
|
||||
}
|
||||
let sqrt_end = f64::sqrt(end as f64) as usize;
|
||||
|
||||
impl Worker {
|
||||
pub fn new(primes_list:Rc<RefCell<VecDeque<u64>>>) -> Worker {
|
||||
Worker {
|
||||
prime_list: primes_list,
|
||||
for p in known_primes {
|
||||
let prime = *p as usize;
|
||||
if prime > sqrt_end {
|
||||
break;
|
||||
}
|
||||
|
||||
let modu = start % prime;
|
||||
let mut mult = if modu == 0 {
|
||||
start
|
||||
} else {
|
||||
start + prime - modu
|
||||
};
|
||||
while mult < end {
|
||||
sieve[mult - start] = false;
|
||||
mult += prime;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&mut self) {
|
||||
for i in 0..(end - start) {
|
||||
if sieve[i] {
|
||||
let prime = i + start;
|
||||
found_primes.push(prime as u64);
|
||||
|
||||
let mut mult = prime * prime;
|
||||
while mult < end {
|
||||
sieve[mult - start] = false;
|
||||
mult += prime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
found_primes
|
||||
}
|
||||
|
||||
28
test.sh
28
test.sh
@@ -17,9 +17,12 @@ fi
|
||||
tests=0
|
||||
passed=0
|
||||
|
||||
## TEST
|
||||
((tests++))
|
||||
echo -n "${tests}: Find 5th prime number..."
|
||||
if [[ $("$BINARY" 5) == 11 ]]
|
||||
echo -n "${tests}: Find all prime numbers before 70..."
|
||||
expect="2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 "
|
||||
|
||||
if [ "$("$BINARY" -v 70 | tr '\n' ' ')" = "$expect" ]
|
||||
then
|
||||
echo " pass"
|
||||
((passed++))
|
||||
@@ -27,6 +30,20 @@ else
|
||||
echo " FAIL"
|
||||
fi
|
||||
|
||||
## TEST
|
||||
((tests++))
|
||||
echo -n "${tests}: Find last prime before 1,000,000,000..."
|
||||
expect="999999937"
|
||||
|
||||
if [ "$("$BINARY" 1000000000)" = "$expect" ]
|
||||
then
|
||||
echo " pass"
|
||||
((passed++))
|
||||
else
|
||||
echo " FAIL"
|
||||
fi
|
||||
|
||||
## TEST
|
||||
((tests++))
|
||||
echo -n "${tests}: 11 is prime..."
|
||||
if "$BINARY" -t 11
|
||||
@@ -37,6 +54,7 @@ else
|
||||
echo " FAIL"
|
||||
fi
|
||||
|
||||
## TEST
|
||||
((tests++))
|
||||
echo -n "${tests}: 9 is not prime..."
|
||||
if ! "$BINARY" -t 9
|
||||
@@ -47,4 +65,10 @@ else
|
||||
echo " FAIL"
|
||||
fi
|
||||
|
||||
## RESULTS
|
||||
echo "Results: $passed/$tests"
|
||||
|
||||
if [ $passed -ne $tests ]
|
||||
then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
Reference in New Issue
Block a user