Pandigital prime

From Rosetta Code
Revision as of 16:48, 4 September 2021 by PureFox (talk | contribs) (Tidied task description a bit.)
Pandigital prime is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

The following problem is taken from Project Euler.

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

Assume that the problem is talking about decimal numbers.

Ring

<lang ring> load "stdlib.ring" see "working..." + nl see "The largest pandigital prime is:" + nl

limit = 9876543

for n = limit to 2 step -2

   flag = 1
   strn = string(n) 
   if isprime(n)
      for m = 1 to len(strn)
          ind = count(strn,strn[m])
          if ind != 1
             flag = 0
          ok
      next
      if flag = 1
         pand = n
         exit
      ok           
   ok

next

see "" + pand + nl

see "done..." + nl

func count(cString,dString)

    sum = 0
    while substr(cString,dString) > 0
          sum++
          cString = substr(cString,substr(cString,dString)+len(string(sum)))
    end
    return sum

</lang>

Output:
The largest pandigital prime is:
9,876,413

Wren

Library: Wren-math
Library: Wren-fmt

<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 1..n once is:") for (n in 9..1) {

   var perms = permutations.call((1..n).toList)
   for (i in perms.count - 1..0) {
       if (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>

Output:
The largest pandigital decimal prime which uses all the digits 1..n once is:
7,652,413