devela/num/int/wrapper/impl_prime.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
// devela::num::int::wrapper::impl_prime
//
//! Implements prime-related methods for [`Int`].
//
// TOC
// - signed|unsigned:
// - is_prime
// - prime_nth
// - prime_pi
// - totient
use super::super::shared_docs::*;
#[cfg(feature = "_int_isize")]
use crate::isize_up;
#[cfg(feature = "_int_usize")]
use crate::usize_up;
use crate::{iif, paste, Int, NumError::Overflow, NumResult as Result};
/// Implements prime-related methods for [`Int`].
///
/// # Args
/// $t: the input/output type
/// $up: the upcasted type to do the operations on (for prime_pi)
/// $cap: the capability feature that enables the given implementation. E.g "_int_i8".
/// $cmp: the feature that enables the given implementation. E.g "_cmp_i8".
///
/// $d: the doclink suffix for the method name
macro_rules! impl_prime {
() => {
impl_prime![signed
i8 |i16 :"_int_i8" :"_cmp_i8" | "",
i16 |i32 :"_int_i16" :"_cmp_i16" | "-1",
i32 |i64 :"_int_i32" :"_cmp_i32" | "-2",
i64 |i128 :"_int_i64" :"_cmp_i64" | "-3",
i128 |i128 :"_int_i128" :"_cmp_i128" | "-4",
isize |isize_up :"_int_isize" :"_cmp_isize" | "-5"
];
impl_prime![unsigned
u8 |u16 :"_int_u8" :"_cmp_u8" | "-6",
u16 |u32 :"_int_u16" :"_cmp_u16" | "-7",
u32 |u64 :"_int_u32" :"_cmp_u32" | "-8",
u64 |u128 :"_int_u64" :"_cmp_u64" | "-9",
u128 |u128 :"_int_u128" :"_cmp_u128" | "-10",
usize |usize_up :"_int_usize" /*_cmp_usize*/ | "-11" // always available
];
};
(signed $( $t:ty | $up:ty : $cap:literal $(: $cmp:literal)? | $d:literal ),+) => {
$( impl_prime![@signed $t|$up:$cap $(:$cmp)? | $d]; )+
};
(unsigned $( $t:ty | $up:ty : $cap:literal $(: $cmp:literal)? | $d:literal ),+) => {
$( impl_prime![@unsigned $t|$up:$cap $(:$cmp)? | $d]; )+
};
(
// implements signed ops
@signed $t:ty | $up:ty : $cap:literal $(: $cmp:literal)? | $d:literal) => { paste! {
#[doc = crate::doc_availability!(feature = $cap)]
///
#[doc = "# Integer prime-related methods for `" $t "`\n\n"]
#[doc = "- [is_prime](#method.is_prime" $d ")"]
#[doc = "- [prime_nth](#method.prime_nth" $d ")"]
#[doc = "- [prime_pi](#method.prime_pi" $d ")"]
#[doc = "- [totient](#method.totient" $d ")"]
///
#[cfg(feature = $cap )]
impl Int<$t> {
/// Returns `true` if `n` is prime.
///
/// This approach uses optimized trial division, which means it checks
/// only odd numbers starting from 3 and up to the square root of the
/// given number. This is based on the fact that if a number is
/// divisible by a number larger than its square root, the result of the
/// division will be smaller than the square root, and it would have
/// already been checked in previous iterations.
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert![Int(127_" $t ").is_prime()];"]
#[doc = "assert![Int(2_" $t ").is_prime()];"]
#[doc = "assert![!Int(1_" $t ").is_prime()];"]
#[doc = "assert![!Int(-2_" $t ").is_prime()];"]
/// ```
$(
/// # Features
#[doc = "This will only be *const* if the " $cmp " feature is enabled."]
#[cfg(feature = $cmp)]
)? // $cmp
#[must_use]
pub const fn is_prime(self) -> bool {
match self.0 {
..=1 => false,
2..=3 => true,
_ => {
iif![self.0 % 2 == 0; return false];
let limit = iif![let Ok(s) = self.sqrt_floor(); s.0; unreachable!()];
let mut i = 3;
while i <= limit { iif![self.0 % i == 0; return false]; i += 2; }
true
}
}
}
$( // $cmp
#[cfg(not(feature = $cmp))] #[allow(missing_docs)]
pub fn is_prime(self) -> bool {
match self.0 {
..=1 => false,
2..=3 => true,
_ => {
iif![self.0 % 2 == 0; return false];
let limit = iif![let Ok(s) = self.sqrt_floor(); s.0; unreachable!()];
let mut i = 3;
while i <= limit { iif![self.0 % i == 0; return false]; i += 2; }
true
}
}
}
)?
/// Finds the 0-indexed `nth` prime number.
///
/// Note: If `nth` is negative, this function treats it as its absolute
/// value. For example, a value of `-3` will be treated as `3`, and the
/// function will return the 3rd prime number.
/// # Errors
/// Returns [`Overflow`] if the result can't fit the type.
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert_eq![Ok(Int(2)), Int(0_" $t ").prime_nth()];"]
#[doc = "assert_eq![Ok(Int(3)), Int(1_" $t ").prime_nth()];"]
#[doc = "assert_eq![Ok(Int(127)), Int(30_" $t ").prime_nth()];"]
#[doc = "assert_eq![Ok(Int(127)), Int(-30_" $t ").prime_nth()];"]
/// # #[cfg(feature = "_int_i8")]
/// assert![Int(31_i8).prime_nth().is_err()];
/// ```
$(
/// # Features
#[doc = "This will only be *const* if the " $cmp " feature is enabled."]
#[cfg(feature = $cmp)]
)? // $cmp
pub const fn prime_nth(self) -> Result<Int<$t>> {
let [nth, mut count, mut i] = [self.0.abs(), 1, 2];
loop {
if Int(i).is_prime() {
iif![count - 1 == nth; return Ok(Int(i))];
count += 1;
}
i = iif![let Some(i) = i.checked_add(1); i; return Err(Overflow(None))];
}
}
$( // $cmp
#[cfg(not(feature = $cmp))] #[allow(missing_docs)]
pub fn prime_nth(self) -> Result<Int<$t>> {
let [nth, mut count, mut i] = [self.0.abs(), 1, 2];
loop {
if Int(i).is_prime() {
iif![count - 1 == nth; return Ok(Int(i))];
count += 1;
}
i = iif![let Some(i) = i.checked_add(1); i; return Err(Overflow(None))];
}
}
)?
/// Counts the number of primes upto and including `n`.
///
#[doc = NOTATION_PI!()]
///
#[doc = "It upcasts internally to [`" $up "`] for the inner operations."]
/// # Panics
/// It can panic if `n == i128|u128`, at the last iteration of a loop
/// that would take an unfeasable amount of time.
///
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert_eq![1, Int(2_" $t ").prime_pi()];"]
#[doc = "assert_eq![2, Int(3_" $t ").prime_pi()];"]
#[doc = "assert_eq![31, Int(127_" $t ").prime_pi()];"]
#[doc = "assert_eq![0, Int(-5_" $t ").prime_pi()];"]
/// ```
/// # Links
/// - <https://mathworld.wolfram.com/PrimeCountingFunction.html>.
/// - <https://en.wikipedia.org/wiki/Prime-counting_function>.
$(
/// # Features
#[doc = "This will only be *const* if the " $cmp " feature is enabled."]
#[cfg(feature = $cmp)]
)? // $cmp
pub const fn prime_pi(self) -> usize {
let (mut prime_count, mut i) = (0_usize, 0 as $up);
while i <= self.0 as $up {
iif![Int(i as $t).is_prime(); prime_count += 1];
i += 1;
}
prime_count
}
$( // $cmp
#[cfg(not(feature = $cmp))] #[allow(missing_docs)]
pub fn prime_pi(self) -> usize {
let (mut prime_count, mut i) = (0_usize, 0 as $up);
while i <= self.0 as $up {
iif![Int(i as $t).is_prime(); prime_count += 1];
i += 1;
}
prime_count
}
)?
/// Counts the number of integers $<|n|$ that are relatively prime to `n`.
///
/// Note: If `n` is negative, this function treats it as its absolute
/// value. For example, a value of `-3` will be treated as `3`.
///
/// # Formulation
/// ## Algorithm
#[doc = ALGORITHM_TOTIENT!()]
///
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert_eq![Int(2), Int(4_" $t ").totient()];"]
#[doc = "assert_eq![Int(6), Int(9_" $t ").totient()];"]
#[doc = "assert_eq![Int(12), Int(13_" $t ").totient()];"]
#[doc = "assert_eq![Int(22), Int(-23_" $t ").totient()];"]
#[doc = "assert_eq![Int(2), Int(-3_" $t ").totient()];"]
/// ```
/// # Links
/// - <https://en.wikipedia.org/wiki/Euler%27s_totient_function>.
#[must_use]
pub const fn totient(self) -> Int<$t> {
let (mut n, mut result, mut i) = (self.0.abs(), self.0.abs(), 2);
while i * i <= n {
if n % i == 0 {
while n % i == 0 { n /= i; }
result -= result / i;
}
i += 1;
}
iif![n > 1; result -= result / n];
Int(result)
}
}
}};
(
// implements unsigned ops
@unsigned $t:ty | $up:ty : $cap:literal $(: $cmp:literal)? | $d:literal) => { paste! {
#[doc = crate::doc_availability!(feature = $cap)]
///
#[doc = "# Integer prime-related methods for `" $t "`\n\n"]
#[doc = "- [is_prime](#method.is_prime" $d ")"]
#[doc = "- [prime_nth](#method.prime_nth" $d ")"]
#[doc = "- [prime_pi](#method.prime_pi" $d ")"]
#[doc = "- [totient](#method.totient" $d ")"]
///
#[cfg(feature = $cap )]
impl Int<$t> {
/// Returns `true` if `n` is prime.
///
/// This approach uses optimized trial division, which means it checks
/// only odd numbers starting from 3 and up to the square root of the
/// given number. This is based on the fact that if a number is
/// divisible by a number larger than its square root, the result of the
/// division will be smaller than the square root, and it would have
/// already been checked in previous iterations.
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert![Int(127_" $t ").is_prime()];"]
#[doc = "assert![Int(2_" $t ").is_prime()];"]
#[doc = "assert![!Int(1_" $t ").is_prime()];"]
/// ```
$(
/// # Features
#[doc = "This will only be *const* if the " $cmp " feature is enabled."]
#[cfg(feature = $cmp)]
)? // $cmp
#[must_use]
pub const fn is_prime(self) -> bool {
match self.0 {
..=1 => false,
2..=3 => true,
_ => {
iif![self.0 % 2 == 0; return false];
let limit = self.sqrt_floor().0;
let mut i = 3;
while i <= limit { iif![self.0 % i == 0; return false]; i += 2; }
true
}
}
}
$( // $cmp
#[cfg(not(feature = $cmp))] #[allow(missing_docs)]
pub fn is_prime(self) -> bool {
match self.0 {
..=1 => false,
2..=3 => true,
_ => {
iif![self.0 % 2 == 0; return false];
let limit = self.sqrt_floor().0;
let mut i = 3;
while i <= limit { iif![self.0 % i == 0; return false]; i += 2; }
true
}
}
}
)?
/// Finds the 0-indexed `nth` prime number.
/// # Errors
/// Returns [`Overflow`] if the result can't fit the type.
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert_eq![Ok(Int(2)), Int(0_" $t ").prime_nth()];"]
#[doc = "assert_eq![Ok(Int(3)), Int(1_" $t ").prime_nth()];"]
#[doc = "assert_eq![Ok(Int(251)), Int(53_" $t ").prime_nth()];"]
/// assert![Int(54_u8).prime_nth().is_err()];
/// ```
$(
/// # Features
#[doc = "This will only be *const* if the " $cmp " feature is enabled."]
#[cfg(feature = $cmp)]
)? // $cmp
pub const fn prime_nth(self) -> Result<Int<$t>> {
let [nth, mut count, mut i] = [self.0, 1, 2];
loop {
if Int(i).is_prime() {
iif![count - 1 == nth; return Ok(Int(i))];
count += 1;
}
i = iif![let Some(i) = i.checked_add(1); i; return Err(Overflow(None))];
}
}
$( // $cmp
#[cfg(not(feature = $cmp))] #[allow(missing_docs)]
pub fn prime_nth(self) -> Result<Int<$t>> {
let [nth, mut count, mut i] = [self.0, 1, 2];
loop {
if Int(i).is_prime() {
iif![count - 1 == nth; return Ok(Int(i))];
count += 1;
}
i = iif![let Some(i) = i.checked_add(1); i; return Err(Overflow(None))];
}
}
)?
/// Counts the number of primes upto and including `n`.
///
#[doc = NOTATION_PI!()]
///
#[doc = "It upcasts internally to [`" $up "`] for the inner operations."]
/// # Panics
/// It can panic if `n == i128|u128`, at the last iteration of a loop
/// that would take an unfeasable amount of time.
///
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert_eq![1, Int(2_" $t ").prime_pi()];"]
#[doc = "assert_eq![2, Int(3_" $t ").prime_pi()];"]
#[doc = "assert_eq![31, Int(127_" $t ").prime_pi()];"]
/// ```
/// # Links
/// - <https://mathworld.wolfram.com/PrimeCountingFunction.html>.
/// - <https://en.wikipedia.org/wiki/Prime-counting_function>.
$(
/// # Features
#[doc = "This will only be *const* if the " $cmp " feature is enabled."]
#[cfg(feature = $cmp)]
)? // $cmp
pub const fn prime_pi(self) -> usize {
let (mut prime_count, mut i) = (0_usize, 0 as $up);
while i <= self.0 as $up {
iif![Int(i as $t).is_prime(); prime_count += 1];
i += 1;
}
prime_count
}
$( // $cmp
#[cfg(not(feature = $cmp))] #[allow(missing_docs)]
pub fn prime_pi(self) -> usize {
let (mut prime_count, mut i) = (0_usize, 0 as $up);
while i <= self.0 as $up {
iif![Int(i as $t).is_prime(); prime_count += 1];
i += 1;
}
prime_count
}
)?
/// Counts the number of integers $<n$ that are relatively prime to `n`.
///
/// # Formulation
/// ## Algorithm
#[doc = ALGORITHM_TOTIENT!()]
///
/// # Examples
/// ```
/// # use devela::Int;
#[doc = "assert_eq![Int(2), Int(4_" $t ").totient()];"]
#[doc = "assert_eq![Int(6), Int(9_" $t ").totient()];"]
#[doc = "assert_eq![Int(12), Int(13_" $t ").totient()];"]
/// ```
/// # Links
/// - <https://en.wikipedia.org/wiki/Euler%27s_totient_function>.
#[must_use]
pub const fn totient(self) -> Int<$t> {
let (mut n, mut result, mut i) = (self.0, self.0, 2);
while i * i <= n {
if n % i == 0 {
while n % i == 0 { n /= i; }
result -= result / i;
}
i += 1;
}
iif![n > 1; result -= result / n];
Int(result)
}
}
}};
}
impl_prime!();