Pandigital prime: Difference between revisions
Content added Content deleted
m (→with 0: sp) |
(→{{header|Wren}}: Added a 0..n digit version.) |
||
Line 480: | Line 480: | ||
{{libheader|Wren-math}} |
{{libheader|Wren-math}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
===Using digits 1 to n=== |
|||
This makes use of the optimization in the Factor entry. |
This makes use of the optimization in the Factor entry. |
||
<lang ecmascript>import "/math" for Int |
<lang ecmascript>import "/math" for Int |
||
Line 528: | Line 529: | ||
The largest pandigital decimal prime which uses all the digits 1..n once is: |
The largest pandigital decimal prime which uses all the digits 1..n once is: |
||
7,652,413 |
7,652,413 |
||
</pre> |
|||
===Using digits 0 to n=== |
|||
Applying the Factor logic for the digits 0..n, we only need to check 8, 5 and 3 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, 2]) { |
|||
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 |
|||
</pre> |
</pre> |