Primality by trial division: Difference between revisions

Content added Content deleted
Line 3,040: Line 3,040:
following the Raku example, which states, "Integer $i is prime if it is greater than one and is divisible by none of 2, 3, up to the square root of $i" (plus an adjustment for the prime number 2)
following the Raku example, which states, "Integer $i is prime if it is greater than one and is divisible by none of 2, 3, up to the square root of $i" (plus an adjustment for the prime number 2)


<syntaxhighlight lang="langur">
Below, we use an implied parameter (.i) on the .isPrime function.
val isPrime = fn(i) {

i == 2 or i > 2 and
<syntaxhighlight lang="langur">val .isPrime = fn(.i) {
not any(fn x:i div x, pseries(2 .. i ^/ 2))
.i == 2 or .i > 2 and
not any fn(.x) { .i div .x }, pseries 2 .. .i ^/ 2
}
}


writeln filter .isPrime, series 100</syntaxhighlight>
writeln filter(isPrime, series(100))
</syntaxhighlight>


=== Recursive ===
=== Recursive ===
{{trans|Go}}
{{trans|Go}}
<syntaxhighlight lang="langur">val .isPrime = fn(.i) {
<syntaxhighlight lang="langur">
val .n = abs(.i)
val isPrime = fn(i) {
if .n <= 2: return .n == 2
val n = abs(i)
if n <= 2: return n == 2


val .chkdiv = fn(.n, .i) {
val chkdiv = fn(n, i) {
if .i * .i <= .n {
if i * i <= n {
return .n ndiv .i and self(.n, .i+2)
return n ndiv i and self(n, i+2)
}
}
return true
return true
}
}


return .n ndiv 2 and .chkdiv(.n, 3)
return n ndiv 2 and chkdiv(n, 3)
}
}


writeln filter .isPrime, series 100</syntaxhighlight>
writeln filter(isPrime, series(100))
</syntaxhighlight>


{{out}}
{{out}}