How to resolve the algorithm Wilson primes of order n step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Wilson primes of order n step by step in the Rust programming language

Table of Contents

Problem Statement

A Wilson prime of order n is a prime number   p   such that   p2   exactly divides:

If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563.

Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Wilson primes of order n step by step in the Rust programming language

Source code in the rust programming language

// [dependencies]
// rug = "1.13.0"

use rug::Integer;

fn generate_primes(limit: usize) -> Vec<usize> {
    let mut sieve = vec![true; limit >> 1];
    let mut p = 3;
    let mut sq = p * p;
    while sq < limit {
        if sieve[p >> 1] {
            let mut q = sq;
            while q < limit {
                sieve[q >> 1] = false;
                q += p << 1;
            }
        }
        sq += (p + 1) << 2;
        p += 2;
    }
    let mut primes = Vec::new();
    if limit > 2 {
        primes.push(2);
    }
    for i in 1..sieve.len() {
        if sieve[i] {
            primes.push((i << 1) + 1);
        }
    }
    primes
}

fn factorials(limit: usize) -> Vec<Integer> {
    let mut f = vec![Integer::from(1)];
    let mut factorial = Integer::from(1);
    f.reserve(limit);
    for i in 1..limit {
        factorial *= i as u64;
        f.push(factorial.clone());
    }
    f
}

fn main() {
    let limit = 11000;
    let f = factorials(limit);
    let primes = generate_primes(limit);
    println!(" n | Wilson primes\n--------------------");
    let mut s = -1;
    for n in 1..=11 {
        print!("{:2} |", n);
        for p in &primes {
            if *p >= n {
                let mut num = Integer::from(&f[n - 1] * &f[*p - n]);
                num -= s;
                if num % ((p * p) as u64) == 0 {
                    print!(" {}", p);
                }
            }
        }
        println!();
        s = -s;
    }
}


  

You may also check:How to resolve the algorithm Safe addition step by step in the C programming language
You may also check:How to resolve the algorithm Identity matrix step by step in the Eiffel programming language
You may also check:How to resolve the algorithm String append step by step in the jq programming language
You may also check:How to resolve the algorithm Average loop length step by step in the REXX programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Standard ML programming language