Skip to content

Commit

Permalink
Merge pull request #3 from evrhines/fix_primality_tests
Browse files Browse the repository at this point in the history
Fix broken miller-rabin primality test
  • Loading branch information
AtropineTears authored Dec 6, 2021
2 parents 0a46ac6 + 9674654 commit a5cc125
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ fn miller_rabin(candidate: &BigUint, limit: usize) -> bool {
*/

let (d,s) = rewrite(&candidate);
let step = s.sub(&one).to_usize().unwrap();

let mut rng = rand::thread_rng();

Expand All @@ -366,10 +367,10 @@ fn miller_rabin(candidate: &BigUint, limit: usize) -> bool {
else {
// Convert To Usizes For Loop
// step = (s - 1)
let step = s.sub(&one).to_usize().unwrap();
let one_usize = one.to_usize().unwrap();
let zero_usize = zero.to_usize().unwrap();

let mut break_early = false;
// Issue #1 | Changed one_usize to zero_usize; step (s-1) was equal to iterations-1 and therefore needed an extra iteration
for _ in zero_usize..step {
x = x.modpow(&two,candidate);
Expand All @@ -381,11 +382,15 @@ fn miller_rabin(candidate: &BigUint, limit: usize) -> bool {
return false
}
else if x == (candidate - BigUint::one()) {
break_early = true;
break;
}

}
return false

if !break_early {
return false
}
}
}
return true
Expand Down
13 changes: 13 additions & 0 deletions tests/primality.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use num_bigint::BigUint;
use num_primes::Verification;

#[test]
fn primality_test() {
let big_prime = BigUint::parse_bytes(b"169511182982703321453314585423962898651587669459838234386506572286328885534468792292646838949809616446341407457141008401355628947670484184607678853094537849610289912805960069455687743151708433319901176932959509872662610091644590437761688516626993416011399330087939042347256922771590903190536793274742859624657", 10).unwrap();
let med_prime = BigUint::parse_bytes(b"17957", 10).unwrap();
let small_prime = BigUint::parse_bytes(b"5", 10).unwrap();

assert!(Verification::is_prime(&small_prime));
assert!(Verification::is_prime(&med_prime));
assert!(Verification::is_prime(&big_prime));
}

0 comments on commit a5cc125

Please sign in to comment.