Pandigital prime: Difference between revisions

→‎{{header|Wren}}: Combined the two versions into 1.
(→‎{{header|Wren}}: Combined the two versions into 1.)
Line 468:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<br>
===Using digits 1 to n===
This makes use of the optimization strategy in the Factor entry to do both the basic and optional tasks.
<lang ecmascript>import "/math" for Int
import "/fmt" for Fmt
Line 483:
while (a[i] > a[i+1]) i = i - 1
while (a[j] < a[i]) j = j - 1
var t = a[.swap(i], j)
a[i] = a[j]
a[j] = t
j = n
i = i + 1
while (i < j) {
t = a[.swap(i], j)
a[i] = a[j]
a[j] = t
i = i + 1
j = j - 1
Line 500 ⟶ 496:
}
 
for (nstart in [7, 4]1..0) {
System.print("The largest pandigital decimal prime which uses all the digits 1..n once is:")
var permsouter = [input]false
for (n in [7, 4]) {
System.print("The largest pandigital decimal prime which uses all the digits 1%(start)..n once is:")
var perms = permutations.call((1..n).toList)
for (in in perms.count[7, - 1..04]) {
ifvar (perms[i][-1] % 2 == 0 || perms[i][-1] == 5permutations.call((start..n).toList) continue
varfor p(i =in Num.fromString(perms[i].join()count - 1..0) {
if (perms[i][0-1] % 2 == "0" || perms[i][-1] %== 25 || (start == 0 ||&& perms[i][-10] == 5"0")) continue
if (Int.isPrime(p)) {
Fmt.print("$,d",var p = Num.fromString(perms[i].join())
returnif (Int.isPrime(p)) {
Fmt.print("$,d\n", p)
a[j] outer = ttrue
a[i] = a[j] break
a[i] = a[j] }
}
if (Int.isPrime(p)outer) {break
}
}</lang>
Line 517 ⟶ 518:
The largest pandigital decimal prime which uses all the digits 1..n once is:
7,652,413
</pre>
===Using digits 0 to n===
Applying the Factor logic for the digits 0..n, we only need to check 8 and 5 digit cases as it can't be any of the others.
<lang ecmascript>import "/math" for Int
import "/fmt" for Fmt
 
// generates all permutations in lexicographical order
var permutations = Fn.new { |input|
var perms = [input]
var a = input.toList
var n = a.count - 1
for (c in 1...Int.factorial(n+1)) {
var i = n - 1
var j = n
while (a[i] > a[i+1]) i = i - 1
while (a[j] < a[i]) j = j - 1
var t = a[i]
a[i] = a[j]
a[j] = t
j = n
i = i + 1
while (i < j) {
t = a[i]
a[i] = a[j]
a[j] = t
i = i + 1
j = j - 1
}
perms.add(a.toList)
}
return perms
}
 
System.print("The largest pandigital decimal prime which uses all the digits 0..n once is:")
for (n in [7, 4]) {
var perms = permutations.call((0..n).toList)
for (i in perms.count - 1..0) {
if (perms[i][0] == "0" || perms[i][-1] % 2 == 0 || perms[i][-1] == 5) continue
var p = Num.fromString(perms[i].join())
if (Int.isPrime(p)) {
Fmt.print("$,d", p)
return
}
}
}</lang>
 
{{out}}
<pre>
The largest pandigital decimal prime which uses all the digits 0..n once is:
76,540,231
9,476

edits