How to resolve the algorithm Sequence of primes by trial division step by step in the Crystal programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sequence of primes by trial division step by step in the Crystal programming language

Table of Contents

Problem Statement

Generate a sequence of primes by means of trial division.

Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sequence of primes by trial division step by step in the Crystal programming language

Source code in the crystal programming language

require "big"

def primep5?(n)                          # P5 Prime Generator primality test
  # P5 = 30*k + {7,11,13,17,19,23,29,31} # P5 primes candidates sequence
  n = n.to_big_i
  return [2, 3, 5].includes?(n) if n < 7 # for small and negative values
  return false if n.gcd(30) != 1         # 4/15 (8/30) of integers are P5 pc
  p = typeof(n).new(7)                   # first P5 sequence value
  until p*p > n
    return false if                      # if n is composite
      n % (p)    == 0 || n % (p+4)  == 0 || n % (p+6)  == 0 || n % (p+10) == 0 ||
      n % (p+12) == 0 || n % (p+16) == 0 || n % (p+22) == 0 || n % (p+24) == 0
      p += 30  # first prime candidate for next kth residues group
  end
  true
end

# Create sequence of primes from 1_000_000_001 to 1_000_000_201
n = 1_000_000_001; n.step(to: n+200, by: 2) { |p| puts p if primep5?(p) }


  

You may also check:How to resolve the algorithm Zero to the zero power step by step in the Asymptote programming language
You may also check:How to resolve the algorithm Zig-zag matrix step by step in the jq programming language
You may also check:How to resolve the algorithm Comments step by step in the SQL programming language
You may also check:How to resolve the algorithm Machine code step by step in the Swift programming language
You may also check:How to resolve the algorithm Dynamic variable names step by step in the Erlang programming language