3个版本
0.1.2 | 2020年7月27日 |
---|---|
0.1.1 | 2020年7月27日 |
0.1.0 | 2020年7月4日 |
在数学类别中排名第1678
每月下载量73次
17KB
181 行
素数迭代器和计算
此库提供了一种迭代素数的结构,以及计算素数因子和将数字分类为素数或合数的方法。
使用此库
将以下内容添加到您的 Cargo.toml
文件中
[dependencies]
elr_primes = "0.1.2"
示例
基本用法
use elr_primes::Primes;
// Provides an iterator for all prime numbers less than or equal to 1000
let mut p = Primes::new(1000);
一旦结构被初始化,primes()
方法提供了一个素数的迭代器。
# use elr_primes::Primes;
let p = Primes::new(10); // Primes less than or equal to 10
let mut prime_iter = p.primes();
let primes: Vec<usize> = prime_iter.copied().collect();
let expected: [usize; 4] = [2, 3, 5, 7];
assert_eq!(primes, expected);
由于 primes()
返回一个迭代器,您也可以直接用它来查找特定的素数。
# use elr_primes::Primes;
let p = Primes::new(100); // Primes less than or equal to 100
let n = 20;
// Iterators are zero-based, so to get the 20th prime we need to search for the 19th
match p.primes().nth(n - 1) {
Some(x) => println!("The {}th prime is: {}", n, x),
None => println!("The {}th prime is outside the current bounds", n)
};
还有方法可以找到数字的素数因子,以及一个数字是素数还是合数。
use elr_primes::{Primes, Primality};
let p = Primes::new(100);
let n = 96;
match p.factors(n) {
Ok(factors) => println!("{:?}", factors),
Err(_) => println!("Could not find all prime factors within the bounds"),
};
let n = 23;
match p.primality(n) {
Primality::Prime => println!("{} is prime", n),
Primality::Composite => println!("{} is composite", n),
Primality::Unknown => println!("Primality of {} is undetermined", n),
};