Skip to content

Move sieve optimization into the primality check - #48

Merged
survived merged 2 commits into
mfrom
optimize-primality-check
Oct 16, 2026
Merged

survived merged 2 commits into
mfrom
optimize-primality-check

Conversation

@survived

@survived survived commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Perf difference:

  • Time it takes to do 10000 primality tests on random odd 1000-bits integers
    • Nbi: v0.3.2: 0.77-0.84s; m: 3.30-3.34s; this PR: 0.55-0.57s
    • Rug: v0.3.2: 0.32-0.34s; m: 0.32-0.34s; this PR: 0.09s
  • Generate 1000-bits prime, 10 times
    • Nbi: v0.3.2: 0.25-0.30s; m: 0.84-1.68s; this PR: 0.19s
    • Rug: v0.3.2: 0.09-0.15s; m: 0.08s-0.12s; this PR: 0.08s
  • Generate 1000-bits safe prime, 10 times (with the same RNG seed)
    • Nbi: v0.3.2: 35.86s; m: 185.94s; this PR: 23.63s
    • Rug: v0.3.2: 11.92s; m: 11.92s; this PR: 10.47s
Code used for benchmarks

#[test]
fn is_prime_many_times() {
    for _ in 0..10000 {
        let mut x = Integer::random_bits(1000, &mut rand_core::OsRng);
        x |= 1;
        let _ = std::hint::black_box(x.is_probably_prime(25, &mut rand_core::OsRng));
    }
}

#[test]
fn generate_prime() {
    let mut rng = rand_dev::DevRng::new();

    for _ in 0..10 {
        let _x = std::hint::black_box(Integer::generate_prime(&mut rng, 1000));
    }
}

// run with `export RUST_TESTS_SEED=c020d800c74e122683308880e800397634cbb3823e63aaf5045b9b52d537ef8c`
#[test]
fn generate_safe_prime() {
    let mut rng = rand_dev::DevRng::new();

    for _ in 0..10 {
        let _x = std::hint::black_box(Integer::generate_safe_prime(&mut rng, 1000));
    }
}

@survived
survived force-pushed the optimize-primality-check branch from 4f01ce7 to 9f93f63 Compare October 16, 2026 07:50
@maurges

maurges commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

I have a suspicion that crypto-primes does a constant-time primality check

@survived
survived force-pushed the optimize-primality-check branch 3 times, most recently from 29ea731 to 862d0bd Compare October 16, 2026 10:27
Signed-off-by: Denis Varlakov <cordial.egg6523@fastmail.com>
@survived
survived force-pushed the optimize-primality-check branch from 862d0bd to 59c6723 Compare October 16, 2026 10:29
Signed-off-by: Denis Varlakov <cordial.egg6523@fastmail.com>
@survived
survived requested a review from maurges October 16, 2026 10:32
@survived
survived marked this pull request as ready for review October 16, 2026 10:32
@survived
survived merged commit c8566c7 into m Oct 16, 2026
@survived
survived deleted the optimize-primality-check branch October 16, 2026 13:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants