How to resolve the algorithm Sequence of primes by trial division step by step in the Nim 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 Nim 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 Nim programming language
Source code in the nim programming language
import strformat
func isPrime(n: int): bool =
if n < 2: return false
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
true
var count = 1
write(stdout, " 2")
for i in countup(3, 1999, 2):
if isPrime(i):
inc count
write(stdout, fmt"{i:5}")
if count mod 15 == 0:
write(stdout, "\n")
echo()
You may also check:How to resolve the algorithm Brazilian numbers step by step in the RPL programming language
You may also check:How to resolve the algorithm Function composition step by step in the Quackery programming language
You may also check:How to resolve the algorithm Day of the week step by step in the jq programming language
You may also check:How to resolve the algorithm Maximum triangle path sum step by step in the Clojure programming language
You may also check:How to resolve the algorithm Empty program step by step in the ALGOL 68 programming language