Descending primes: Difference between revisions

Nim solution.
(Nim solution.)
Line 790:
{{out}}
<pre>{2, 3, 5, 7, 31, 41, 43, 53, 61, 71, 73, 83, 97, 421, 431, 521, 541, 631, 641, 643, 653, 743, 751, 761, 821, 853, 863, 941, 953, 971, 983, 5431, 6421, 6521, 7321, 7541, 7621, 7643, 8431, 8521, 8543, 8641, 8731, 8741, 8753, 8761, 9421, 9431, 9521, 9631, 9643, 9721, 9743, 9851, 9871, 75431, 76421, 76541, 76543, 86531, 87421, 87541, 87631, 87641, 87643, 94321, 96431, 97651, 98321, 98543, 98621, 98641, 98731, 764321, 865321, 876431, 975421, 986543, 987541, 987631, 8764321, 8765321, 9754321, 9875321, 97654321, 98764321, 98765431}</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/[strutils, sugar]
 
proc isPrime(n: int): bool =
assert n > 7
if n mod 2 == 0 or n mod 3 == 0: return false
var d = 5
var step = 2
while d * d <= n:
if n mod d == 0:
return false
inc d, step
step = 6 - step
result = true
 
iterator descendingPrimes(): int =
 
# Yield one digit primes.
for n in [2, 3, 5, 7]:
yield n
 
# Yield other primes by increasing length and in ascending order.
type Item = tuple[val, lastDigit: int]
var items: seq[Item] = collect(for n in 1..9: (n, n))
for ndigits in 2..9:
var nextItems: seq[Item]
for item in items:
for newDigit in 0..(item.lastDigit - 1):
let newVal = 10 * item.val + newDigit
nextItems.add (val: newVal, lastDigit: newDigit)
if newVal.isPrime():
yield newVal
items = move(nextItems)
 
 
var rank = 0
for prime in descendingPrimes():
inc rank
stdout.write ($prime).align(8)
stdout.write if rank mod 8 == 0: '\n' else: ' '
echo()
</syntaxhighlight>
{{out}}
<pre> 2 3 5 7 31 41 43 53
61 71 73 83 97 421 431 521
541 631 641 643 653 743 751 761
821 853 863 941 953 971 983 5431
6421 6521 7321 7541 7621 7643 8431 8521
8543 8641 8731 8741 8753 8761 9421 9431
9521 9631 9643 9721 9743 9851 9871 75431
76421 76541 76543 86531 87421 87541 87631 87641
87643 94321 96431 97651 98321 98543 98621 98641
98731 764321 865321 876431 975421 986543 987541 987631
8764321 8765321 9754321 9875321 97654321 98764321 98765431
</pre>
 
=={{header|Perl}}==
256

edits