How to resolve the algorithm Primality by trial division step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Primality by trial division step by step in the Wren programming language
Table of Contents
Problem Statement
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime. Use trial division. Even numbers greater than 2 may be eliminated right away. A loop from 3 to √ n will suffice, but other loops are allowed.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Primality by trial division step by step in the Wren programming language
Source code in the wren programming language
import "/fmt" for Fmt
var isPrime = Fn.new { |n|
if (n < 2) return false
if (n%2 == 0) return n == 2
var p = 3
while (p * p <= n) {
if (n%p == 0) return false
p = p + 2
}
return true
}
var tests = [2, 5, 12, 19, 57, 61, 97]
System.print("Are the following prime?")
for (test in tests) {
System.print("%(Fmt.d(2, test)) -> %(isPrime.call(test) ? "yes" : "no")")
}
You may also check:How to resolve the algorithm Balanced brackets step by step in the COBOL programming language
You may also check:How to resolve the algorithm Bifid cipher step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Harshad or Niven series step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Circular primes step by step in the Phix programming language
You may also check:How to resolve the algorithm Start from a main routine step by step in the Phix programming language