Upside-down numbers: Difference between revisions

another Ada solution, based on Phix
(→‎{{header|ALGOL 68}}: typo, comment)
(another Ada solution, based on Phix)
 
(22 intermediate revisions by 13 users not shown)
Line 29:
;* [[oeis:A299539|OEIS:A299539 - Upside-down numbers]]
 
 
=={{header|Ada}}==
===Version 1 (slower, direct from definition)===
<syntaxhighlight lang="ada">
pragma Ada_2022;
 
with Ada.Text_IO;
 
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Sets;
 
procedure Upside_Down_Numbers is
 
-- a rather slow algorithm that proceeds by recursive expansion; i.e.,
-- a straightforward implementation via the definition
 
package IO renames Ada.Text_IO;
 
subtype Digit is Integer range 1 .. 9;
 
Mirror : constant array (Digit) of Digit :=
[for Ith in Digit => 10 - Ith];
 
type Upside_Down_Number is array (Positive range <>) of Digit;
 
procedure Put (Number : Upside_Down_Number) is
package Digit_IO is new IO.Integer_IO (Num => Digit);
begin
for N of Number loop
Digit_IO.Put (N, 0);
end loop;
end Put;
 
package Upside_Down_Vecs is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => Upside_Down_Number);
subtype Upside_Down_Vec is Upside_Down_Vecs.Vector;
 
package Upside_Down_Sets is new Ada.Containers.Indefinite_Ordered_Sets
(Element_Type => Upside_Down_Number);
subtype Upside_Down_Set is Upside_Down_Sets.Set;
 
function Expand_Even (Numbers : Upside_Down_Set) return Upside_Down_Set is
-- if Numbers holds even-length upside-down numbers,
-- this expands them to corresponding odd-length upside-down numbers
 
Result : Upside_Down_Set;
 
Length : constant Positive := Numbers.First_Element'Length;
Half_Length : constant Positive := Length / 2;
 
New_Number : Upside_Down_Number (1 .. Length + 1);
 
begin
 
for Old_Number of Numbers loop
 
for Ith in 1 .. Half_Length loop
New_Number (Ith) := Old_Number (Ith);
New_Number (Length + 1 - Ith + 1) := Old_Number (Length - Ith + 1);
end loop;
 
New_Number (Half_Length + 1) := 5;
if not Result.Contains (New_Number) then
Result.Insert (New_Number);
end if;
 
end loop;
 
return Result;
 
end Expand_Even;
 
function Expand_Odd (Numbers : Upside_Down_Set) return Upside_Down_Set is
-- if Numbers holds odd-length upside-down numbers,
-- this expands them to corresponding even-length upside-down numbers
--
-- alas, this is inefficient not only by exhaustive enumeration,
-- but by generating several numbers more than once
 
Result : Upside_Down_Set;
 
Length : constant Positive := Numbers.First_Element'Length;
Half_Length : constant Positive := (Length + 1) / 2;
 
New_Number : Upside_Down_Number (1 .. Length + 1);
 
begin
 
for Old_Number of Numbers loop
for Breakpoint in 1 .. Half_Length loop
 
for Ith in 1 .. Half_Length loop
 
if Ith < Breakpoint then
New_Number (Ith) := Old_Number (Ith);
New_Number (Length + 1 - Ith + 1) :=
Old_Number (Length - Ith + 1);
 
elsif Ith >= Breakpoint then
New_Number (Ith + 1) := Old_Number (Ith);
New_Number (Length + 1 - Ith) :=
Old_Number (Length - Ith + 1);
end if;
 
end loop;
 
for D in Digit loop
New_Number (Breakpoint) := D;
New_Number (Length + 1 - Breakpoint + 1) := Mirror (D);
if not Result.Contains (New_Number) then
Result.Insert (New_Number);
end if;
end loop;
 
end loop;
end loop;
 
return Result;
 
end Expand_Odd;
 
function Expand (Number : Upside_Down_Set) return Upside_Down_Set is
(if Number.First_Element'Length mod 2 = 0 then Expand_Even (Number)
else Expand_Odd (Number));
 
Iterations : array (1 .. 100) of Upside_Down_Set;
Result : Upside_Down_Vec;
Number_Computed : Positive := 1;
Ith : Positive := 1;
 
begin
IO.Put_Line ("Slow Formula");
IO.Put_Line ("==== =======");
Iterations (1).Insert (Upside_Down_Number'[5]);
Result.Append (Upside_Down_Number'[5]);
while Number_Computed < 5_000_000 loop
Iterations (Ith + 1) := Expand (Iterations (Ith));
Number_Computed := @ + Positive (Iterations (Ith + 1).Length);
for Each of Iterations (Ith + 1) loop
Result.Append (Each);
end loop;
Ith := @ + 1;
end loop;
IO.Put_Line ("Computed" & Number_Computed'Image & " upside-down numbers");
IO.Put ("The first 50: ");
for Ith in 1 .. 50 loop
Put (Result (Ith));
IO.Put (", ");
end loop;
IO.New_Line;
IO.Put ("The 500th: ");
Put (Result (500));
IO.New_Line;
IO.Put ("The 5_000th: ");
Put (Result (5_000));
IO.New_Line;
IO.Put ("The 500_000th: ");
Put (Result (500_000));
IO.New_Line;
IO.Put ("The 5_000_000th: ");
Put (Result (5_000_000));
IO.New_Line;
end Upside_Down_Numbers;
</syntaxhighlight>
{{out}}
<pre>
Slow Formula
==== =======
Computed 5978710 upside-down numbers
The first 50: 5, 19, 28, 37, 46, 55, 64, 73, 82, 91, 159, 258, 357, 456, 555, 654, 753, 852, 951, 1199, 1289, 1379, 1469, 1559, 1649, 1739, 1829, 1919, 2198, 2288, 2378, 2468, 2558, 2648, 2738, 2828, 2918, 3197, 3287, 3377, 3467, 3557, 3647, 3737, 3827, 3917, 4196, 4286, 4376, 4466,
The 500th: 494616
The 5_000th: 56546545
The 500_000th: 729664644183
The 5_000_000th: 82485246852682
</pre>
 
===Version 2===
{{Trans|Phix}}
 
<syntaxhighlight lang="ada">
pragma Ada_2022;
 
with Ada.Text_IO;
 
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Sets;
 
procedure Upside_Down_Numbers is
 
-- This translates the Phix solution, which essentially puts in a formula
-- the roughly quadratic growth of the upside-down numbers.
-- The essential insight is that every even digit increases
-- the number of new numbers generated by a factor of 10.
-- So, there are only 1 upside-down number of length 1,
-- 9 of length 2, 9 of length 3, 81 of length 4, and so forth.
-- From this fact you can navigate your way relatively quickly
-- to the desired number.
 
package IO renames Ada.Text_IO;
 
subtype Digit is Integer range 1 .. 9;
 
Mirror : constant array (Digit) of Digit :=
[for Ith in Digit => 10 - Ith];
 
type Upside_Down_Number is array (Positive range <>) of Digit;
 
procedure Put (Number : Upside_Down_Number) is
package Digit_IO is new IO.Integer_IO (Num => Digit);
begin
for N of Number loop
Digit_IO.Put (N, 0);
end loop;
end Put;
 
function Kth_Of_N (Kth, Digit, Count : Natural) return Upside_Down_Number is
-- we want the Kth integer of Digit length,
-- when we know it is Count from the first of this length
 
New_Count : Natural := Count;
New_Kth : Natural := Kth;
This_Digit : Natural;
 
begin
if Digit = 0 then
return Upside_Down_Number'[];
 
elsif Digit = 1 then
return Upside_Down_Number'[5];
 
else
New_Count := @ / 9;
This_Digit := (New_Kth - 1) / New_Count + 1;
New_Kth := @ - (This_Digit - 1) * New_Count;
 
declare
Temp : Upside_Down_Number :=
Kth_Of_N (New_Kth, Digit - 2, New_Count);
Result : Upside_Down_Number (1 .. Temp'Length + 2) :=
[1 => This_Digit, others => 1];
begin
 
Result (Temp'Last + 2) := Mirror (This_Digit);
for Ith in Temp'Range loop
Result (Ith + 1) := Temp (Ith);
end loop;
return Result;
 
end;
 
end if;
 
end Kth_Of_N;
 
function Phormula (Nth : Positive) return Upside_Down_Number is
-- Find the setup for Nth so that the Kth_Of_N formula works out.
-- This implements the insight mentioned above, that
-- the number of upside-down numbers increases by a factor of 9
-- for every even digit.
 
Digit : Positive := 1; -- number of digits needed
Count : Positive := 1; -- how many we've skipped so far
First : Positive := 1; -- the first u-d number for the current #digits
Last : Positive := 1; -- the last u-d number for the current #digits
 
begin
 
while Nth > Last loop
 
First := Last + 1;
Digit := @ + 1;
 
if Digit mod 2 = 0 then
Count := @ * 9;
end if;
 
Last := First + Count - 1;
end loop;
 
return Kth_Of_N (Nth - First + 1, Digit, Count);
 
end Phormula;
 
begin
IO.Put_Line ("Phast Phormula:");
IO.Put_Line ("===== ========");
IO.Put ("The first 50: ");
for Ith in 1 .. 50 loop
Put (Phormula (Ith));
IO.Put (", ");
end loop;
IO.New_Line;
IO.Put ("The 500th: ");
Put (Phormula (500));
IO.New_Line;
IO.Put ("The 5_000th: ");
Put (Phormula (5_000));
IO.New_Line;
IO.Put ("The 500_000th: ");
Put (Phormula (500_000));
IO.New_Line;
IO.Put ("The 5_000_000th: ");
Put (Phormula (5_000_000));
IO.New_Line;
end Upside_Down_Numbers;
</syntaxhighlight>
{{out}}
<pre>
Phast Phormula:
===== ========
The first 50: 5, 19, 28, 37, 46, 55, 64, 73, 82, 91, 159, 258, 357, 456, 555, 654, 753, 852, 951, 1199, 1289, 1379, 1469, 1559, 1649, 1739, 1829, 1919, 2198, 2288, 2378, 2468, 2558, 2648, 2738, 2828, 2918, 3197, 3287, 3377, 3467, 3557, 3647, 3737, 3827, 3917, 4196, 4286, 4376, 4466,
The 500th: 494616
The 5_000th: 56546545
The 500_000th: 729664644183
The 5_000_000th: 82485246852682
</pre>
 
=={{header|ALGOL 68}}==
Line 151 ⟶ 467:
The 500000000000000th upside down number is the 36744952787041st 32-digit number (12651942383972646483172786195489)
The 5000000000000000th upside down number is the 830704575083359th 34-digit number (1513835774459212468981566335727959)
</pre>
 
=={{header|Basic}}==
==={{header|Applesoft BASIC}}===
 
Beyond 9 digits, rounding errors occur.
<syntaxhighlight lang="basic"> 1 PRINT "THE FIRST 50 UPSIDE DOWN NUMBERS:": FOR I = 1 TO 50: GOSUB 4: NEXT I: PRINT
2 FOR J = 2 TO 10::I = INT (5 * 10 ^ J): PRINT CHR$ (13)I"TH: ";: GOSUB 4: NEXT J
3 END
4 GOSUB 5: PRINT O$;: RETURN
5 IF I > = 1E9 THEN PRINT "?OVERFLOW" + CHR$ (7): END
6 L$ = "":R$ = "":S = I - 1:F = 1:I$(1) = "5": FOR E = 0 TO 1E38: FOR O = F TO 1:R = S:S = S - INT (9 ^ E):F = 0: IF S > = 0 THEN NEXT O,E
7 IF E THEN R = R + .5: FOR D = E - 1 TO 0 STEP - 1:N = INT (R / 9 ^ D):L$ = L$ + STR$ (N + 1):R$ = STR$ (9 - N) + R$:R = R - N * INT (9 ^ D): NEXT D
8 O$ = L$ + I$(O) + R$ + " "
9 RETURN
</syntaxhighlight>
{{out}}
<pre>THE FIRST 50 UPSIDE DOWN NUMBERS:
5 19 28 37 46 55 64 73 82 91 159 258 357 456 555 654 753 852 951 1199 1289 1379 1469 1559 1649 1739 1829 1919 2198 2288 2378 2468 2558 2648 2738 2828 2918 3197 3287 3377 3467 3557 3647 3737 3827 3917 4196 4286 4376 4466
 
500TH: 494616
5000TH: 56546545
50000TH: 6441469664
500000TH: 729664644183
5000000TH: 82485246852682
50000000TH: 9285587463255281
500000000TH: 1436368345672474769
5E+09TH: ?OVERFLOW
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">
function is_ups( n as uinteger ) as boolean
dim as string m = str(n)
dim as uinteger lm = len(m), i
for i = 1 to int(lm/2.0+0.5)
if val(mid(m,i,1)) + val(mid(m,lm-i+1,1)) <> 10 then return false
next i
return true
end function
 
dim as uinteger count, n=0
 
while count<5000001
if is_ups(n) then
count = count + 1
if count < 51 then
print n,
if count mod 5 = 0 then print
end if
if count = 500 or count = 5000 then
print n
end if
end if
n = n + 1
wend
</syntaxhighlight>
<pre>
5 19 28 37 46
55 64 73 82 91
159 258 357 456 555
654 753 852 951 1199
1289 1379 1469 1559 1649
1739 1829 1919 2198 2288
2378 2468 2558 2648 2738
2828 2918 3197 3287 3377
3467 3557 3647 3737 3827
3917 4196 4286 4376 4466
494616
56546545
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="C++">#include <iostream>
#include <vector>
#include <algorithm>
 
bool isUpsideDown( int n ) {
std::vector<int> digits ;
while ( n != 0 ) {
digits.push_back( n % 10 ) ;
n /= 10 ;
}
if ( std::find ( digits.begin( ) , digits.end( ) , 0 ) != digits.end( ) )
return false ;
int forward = 0 ;
int backward = digits.size( ) - 1 ;
while ( forward <= backward ) {
if ( digits[forward] + digits[backward] != 10 )
return false ;
forward++ ;
if ( backward > 0 ) {
backward-- ;
}
}
return true ;
}
 
int main( ) {
int current = 0 ;
int sum = 0 ;
std::vector<int> solution ;
while ( sum != 5000 ) {
current++ ;
if ( isUpsideDown( current ) ) {
solution.push_back( current ) ;
sum++ ;
}
}
std::cout << "The first 50 upside-down numbers:\n" ;
std::cout << "(" ;
for ( int i = 0 ; i < 50 ; i++ )
std::cout << solution[ i ] << ' ' ;
std::cout << ")\n" ;
std::cout << "The five hundredth such number: " << solution[499] << '\n' ;
std::cout << "The five thousandth such number: " << solution[4999] << '\n' ;
return 0 ;
}</syntaxhighlight>
{{out}}
<pre>
The first 50 upside-down numbers:
(5 19 28 37 46 55 64 73 82 91 159 258 357 456 555 654 753 852 951 1199 1289 1379 1469 1559 1649 1739 1829 1919 2198 2288 2378 2468 2558 2648 2738 2828 2918 3197 3287 3377 3467 3557 3647 3737 3827 3917 4196 4286 4376 4466 )
The five hundredth such number: 494616
The five thousandth such number: 56546545
</pre>
 
Line 259 ⟶ 699:
50,000,000th : 9,285,587,463,255,281
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
 
 
function IsUpsideDown(N: integer): boolean;
{Test if N is upsidedown number}
var I,J: integer;
var IA: TIntegerDynArray;
begin
Result:=False;
{Get all digits in the number}
GetDigits(N,IA);
for I:=0 to Length(IA) div 2 do
begin
{Index to right side of number}
J:=High(IA)-I;
{do left and right side add up to 10?}
if IA[J]+IA[I]<>10 then exit;
{No zeros allowed}
if (IA[J]=0) or (IA[I]=0) then exit;
end;
Result:=True;
end;
 
 
procedure ShowUpsideDownNumbers(Memo: TMemo);
var I,J,K: integer;
var Cnt: integer;
var S: string;
begin
Cnt:=0;
S:='';
{Show first 50 upside down numbers}
for I:=5 to high(integer) do
if IsUpsideDown(I) then
begin
Inc(Cnt);
S:=S+Format('%5d',[I]);
if (Cnt mod 10)=0 then S:=S+CRLF;
if Cnt=50 then break;
end;
Memo.Lines.Add(S);
{Show 500th, and 5,000th }
for I:=I to high(integer) do
if IsUpsideDown(I) then
begin
Inc(Cnt);
case Cnt of
500: Memo.Lines.Add(Format(' 500th Upsidedown = %10.0n',[I+0.0]));
5000: Memo.Lines.Add(Format('5,000th Upsidedown = %10.0n',[I+0.0]));
end;
if Cnt>5000 then break;
end;
end;
 
 
 
</syntaxhighlight>
{{out}}
<pre>
5 19 28 37 46 55 64 73 82 91
159 258 357 456 555 654 753 852 951 1199
1289 1379 1469 1559 1649 1739 1829 1919 2198 2288
2378 2468 2558 2648 2738 2828 2918 3197 3287 3377
3467 3557 3647 3737 3827 3917 4196 4286 4376 4466
 
500th Upsidedown = 493,716
5,000th Upsidedown = 56,537,545
 
Elapsed Time: 10.141 Sec.
 
</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="Haskell">import Data.Char ( digitToInt )
import Data.List ( unfoldr , (!!) )
 
findLimits :: (Int , Int) -> [(Int , Int)]
findLimits (st , end ) = unfoldr(\(x , y ) -> if x > y then Nothing else
Just ((x , y ) , (x + 1 , y - 1 ))) (st , end )
 
isUpsideDown :: Int -> Bool
isUpsideDown n
|elem '0' str = False
|otherwise = all (\(a , b ) -> digitToInt( str !! a ) + digitToInt ( str !!
b ) == 10 ) $ findLimits ( 0 , length str - 1 )
where
str = show n
 
main :: IO ( )
main = do
let upsideDowns = take 5000 $ filter isUpsideDown [1..]
putStrLn "The first fifty upside-down numbers!"
print $ take 50 upsideDowns
putStr "The five hundredth such number : "
print $ upsideDowns !! 499
putStr "The five thousandth such number : "
print $ last upsideDowns</syntaxhighlight>
{{out}}
<pre>
The first fifty upside-down numbers!
[5,19,28,37,46,55,64,73,82,91,159,258,357,456,555,654,753,852,951,1199,1289,1379,1469,1559,1649,1739,1829,1919,2198,2288,2378,2468,2558,2648,2738,2828,2918,3197,3287,3377,3467,3557,3647,3737,3827,3917,4196,4286,4376,4466]
The five hundredth such number : 494616
The five thousandth such number : 56546545
</pre>
 
=={{header|jq}}==
Line 406 ⟶ 957:
Five millionth: 82,485,246,852,682
</pre>
 
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="Nim">import std/[math, strformat, strutils, sugar]
 
iterator upsideDownNumbers(): (int, int) =
## Generate upside-down numbers (OEIS A299539).
const
Wrappings = [(1, 9), (2, 8), (3, 7), (4, 6),
(5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]
var
evens = @[19, 28, 37, 46, 55, 64, 73, 82, 91]
odds = @[5]
oddIndex, evenIndex = 0
ndigits = 1
count = 0
 
while true:
if ndigits mod 2 == 1:
if odds.len > oddIndex:
inc count
yield (count, odds[oddIndex])
inc oddIndex
else:
# Build next odds, but switch to evens.
odds = collect:
for (hi, lo) in Wrappings:
for i in odds:
hi * 10^(ndigits + 1) + 10 * i + lo
inc ndigits
oddIndex = 0
else:
if evens.len > evenIndex:
inc count
yield (count, evens[evenIndex])
inc evenIndex
else:
# Build next evens, but switch to odds.
evens = collect:
for (hi, lo) in Wrappings:
for i in evens:
hi * 10^(ndigits + 1) + 10 * i + lo
inc ndigits
evenIndex = 0
 
echo "First fifty upside-downs:"
for (udcount, udnumber) in upsideDownNumbers():
if udcount <= 50:
stdout.write &"{udnumber:5}"
if udcount mod 10 == 0: echo()
elif udcount == 500:
echo &"\nFive hundredth: {insertSep($udnumber)}"
elif udcount == 5_000:
echo &"Five thousandth: {insertSep($udnumber)}"
elif udcount == 50_000:
echo &"Fifty thousandth: {insertSep($udnumber)}"
elif udcount == 500_000:
echo &"Five hundred thousandth: {insertSep($udnumber):}"
elif udcount == 5_000_000:
echo &"Five millionth: {insertSep($udnumber):}"
break
</syntaxhighlight>
 
{{out}}
<pre>First fifty upside-downs:
5 19 28 37 46 55 64 73 82 91
159 258 357 456 555 654 753 852 951 1199
1289 1379 1469 1559 1649 1739 1829 1919 2198 2288
2378 2468 2558 2648 2738 2828 2918 3197 3287 3377
3467 3557 3647 3737 3827 3917 4196 4286 4376 4466
 
Five hundredth: 494_616
Five thousandth: 56_546_545
Fifty thousandth: 6_441_469_664
Five hundred thousandth: 729_664_644_183
Five millionth: 82_485_246_852_682</pre>
 
=={{header|Pascal}}==
Line 595 ⟶ 1,222:
Real time: 0.271 s CPU share: 99.00 %
</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl" line>use v5.36;
use Lingua::EN::Numbers qw(num2en_ordinal);
 
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub table ($c, @V) { my $t = $c * (my $w = 5); ( sprintf( ('%'.$w.'d')x@V, @V) ) =~ s/.{1,$t}\K/\n/gr }
 
sub updown ($n) {
my($i,@ud);
while (++$i) {
next if subset($i, '0', 0) or 0 != ($i+reverse $i) % 10;
my @i = split '', $i;
next if grep { 10 != $i[$_] + $i[$#i-$_] } 0..$#i;
push @ud, $i;
last if $n == @ud;
}
@ud
}
 
my @ud = updown( 5000 );
say "First fifty upside-downs:\n" . table 10, @ud[0..49];
say ucfirst num2en_ordinal($_) . ': ' . comma $ud[$_-1] for 500, 5000;</syntaxhighlight>
{{out}}
<pre>First fifty upside-downs:
5 19 28 37 46 55 64 73 82 91
159 258 357 456 555 654 753 852 951 1199
1289 1379 1469 1559 1649 1739 1829 1919 2198 2288
2378 2468 2558 2648 2738 2828 2918 3197 3287 3377
3467 3557 3647 3737 3827 3917 4196 4286 4376 4466
 
Five hundredth: 494,616
Five thousandth: 56,546,545</pre>
 
=={{header|Phix}}==
Line 662 ⟶ 1,322:
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 12px">
<pre>
The first 50 upside down numbers:
5 19 28 37 46 55 64 73 82 91
Line 771 ⟶ 1,431:
else:
# build next odds, but switch to evens
odds = sorted([hi * 10**(ndigits + 1) + 10 *
i + lo for ihi, lo in oddswrappings for hi, loi in wrappingsodds])
ndigits += 1
odd_index = 0
Line 781 ⟶ 1,441:
else:
# build next evens, but switch to odds
evens = sorted([hi * 10**(ndigits + 1) + 10 *
i + lo for ihi, lo in evenswrappings for hi, loi in wrappingsevens])
ndigits += 1
even_index = 0 even_index = 0
 
 
Line 821 ⟶ 1,481:
Five millionth: 82,485,246,852,682
</pre>
 
=={{header|Quackery}}==
 
(Load extensions for the faster merge sort.)
 
'''Method'''
 
Start with generation zero as the empty string and "5". Make the next generation by expanding the previous generation (<code>expand</code>) i.e. wrapping each of the strings in "1" and "9", "2" and "8" … "8" and "2", "9" and "1". Accumulate the generations. The accumulator starts with "5", after one iteration it has "5", "19", "28" … "82", "91", "159", "258" … "852", "951".
 
Note that this does not produce the numbers in numerical order. It's close to numerical order but not quite there.
So once sufficient numbers have been produced to guarantee that all the numbers in the required range have been calculated, convert them from string format to numerical format and sort, then truncate the list of upside down numbers to the required length.
 
<code>necessary</code> computes a safe number of items to include in the list to guarantee that none are missing from the truncated list - i.e. the length of the list after each iteration of <code>expand</code>. It is <code>(9^n - 5) / 4</code>, where <code>n</code> is the number of iterations. ([https://oeis.org/A211866 OEIS A211866])
 
<code>^</code> in <code>necessary</code> is bitwise XOR, not exponentiation.
 
<syntaxhighlight lang="Quackery"> [ 0
[ 2dup > while
1 ^ 9 * 1+ again ]
nip ] is necessary ( n --> n )
 
[ [] swap
witheach
[ ' [ [ char 1 char 9 ]
[ char 2 char 8 ]
[ char 3 char 7 ]
[ char 4 char 6 ]
[ char 5 char 5 ]
[ char 6 char 4 ]
[ char 7 char 3 ]
[ char 8 char 2 ]
[ char 9 char 1 ] ]
witheach
[ over dip do
dip swap join
swap join nested
rot swap join
swap ]
drop ] ] is expand ( [ --> [ )
 
[ dup necessary temp put
' [ [ char 5 ] ]
' [ [ ] [ char 5 ] ]
[ expand tuck join swap
over size
temp share < not
until ]
drop
temp release
[] swap
witheach
[ $->n drop join ]
sort
swap split drop ] is upsidedowns ( n --> [ )
 
5000 upsidedowns
say "First 50 upside down numbers:"
dup 50 split drop
[] swap witheach
[ number$ nested join ]
45 wrap$
cr cr
say "500th upside down number: "
dup 499 peek echo
cr
say "5000th upside down number: "
4999 peek echo</syntaxhighlight>
 
{{out}}
 
<pre>First 50 upside down numbers:
5 19 28 37 46 55 64 73 82 91 159 258 357 456
555 654 753 852 951 1199 1289 1379 1469 1559
1649 1739 1829 1919 2198 2288 2378 2468 2558
2648 2738 2828 2918 3197 3287 3377 3467 3557
3647 3737 3827 3917 4196 4286 4376 4466
 
500th upside down number: 494616
5000th upside down number: 56546545</pre>
 
=={{header|Raku}}==
Line 852 ⟶ 1,591:
Five hundred thousandth: 729,664,644,183
Five millionth: 82,485,246,852,682</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.8}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ 9 SWAP 2 / CEIL ^ ≫ ''''POW92'''' STO
SWAP 1 - "" SWAP 1 4 ROLL START
9 MOD LAST / FLOOR SWAP
1 + →STR ROT + SWAP NEXT DROP
≫ ''''→STR9'''' STO
≪ → str
≪ "" str SIZE 1 FOR j
106 str j DUP SUB NUM - CHR + -1 STEP
≫ ≫ ''''UDSTR'''' STO
IF DUP 1 == THEN DROP "5" ELSE
1 WHILE OVER 1 > REPEAT
SWAP OVER '''POW92''' - SWAP 1 + END
1 - DUP '''POW92''' ROT + 1 - → series order
≪ order series 2 / CEIL '''→STR9''' DUP
IF order 2 MOD NOT THEN "5" + END
SWAP '''UDSTR''' +
≫ END
≫ ''''UPSDN'''' STO
|
'''POW92''' ''( n -- 9^ceil(n/2) ) ''
'''→STR9''' ''( n str_length -- "12..9" ) ''
n-- ; s = "" ; loop size times
n,m = divmod(n)
append "m+1" to s
return s
'''UDSTR''' ''( "str" -- "rts" )''
s = "" ; loop for j from size(str) downto 1
s[j] = 106 - char(ascii(str[j]))
return s
'''UPSDN''' ''( n -- "a(n)" ) ''
if n = 1 then return "5" else
series = 1 ; while n > 1
n -= 9^ceil(series/2); series++
series-- ; order = n + 9^ceil(series/2) + 1
Create left part of the upside-down number, as a string
Add 5 in the middle if appropriate
Add upside-down right part
et voilà
return full string
|}
{{in}}
<pre>
≪ {} 1 50 FOR j j UPSDN+ NEXT ≫ EVAL
500 UPSDN 5000 UPSDN 50000 UPSDN 500000 UPSDN 5000000 UPSDN
5000000000 UPSDN
</pre>
{{out}}
<pre>
7: { "5" "19" "28" "37" "46" "55" "64" "73" "82" "91" "159" "258" "357" "456" "555" "654" "753" "852" "951" "1199" "1289" "1379" "1469" "1559" "1649" "1739" "1829" "1919" "2198" "2288" "2378" "2468" "2558" "2648" "2738" "2828" "2918" "3197" "3287" "3377" "3467" "3557" "3647" "3737" "3827" "3917" "4196" "4286" "4376" "4466" }
6: "494616"
5: "56546545"
4: "6441469664"
3: "729664644183"
2: "82485246852682"
1: "269222738456273888148"
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">DIGITS =(1..9).to_a
 
updowns = Enumerator.new do |y|
y << 5
(1..).each do |s|
perms = DIGITS.repeated_permutation(s)
perms.each{|perm| y << (perm + perm.reverse.map{|n| 10-n}).join.to_i }
perms.each{|perm| y << (perm + [5] + perm.reverse.map{|n| 10-n}).join.to_i }
end
end
 
res = updowns.take(5000000)
res.first(50).each_slice(10){|slice| puts "%6d"*slice.size % slice}
 
puts
n = 500
5.times do
puts "%8d: %-10d" % [n, res[n-1]]
n *= 10
end
</syntaxhighlight>
{{out}}
<pre> 5 19 28 37 46 55 64 73 82 91
159 258 357 456 555 654 753 852 951 1199
1289 1379 1469 1559 1649 1739 1829 1919 2198 2288
2378 2468 2558 2648 2738 2828 2918 3197 3287 3377
3467 3557 3647 3737 3827 3917 4196 4286 4376 4466
 
500th : 494616
5000th : 56546545
50000th : 6441469664
500000th : 729664644183
5000000th : 82485246852682
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="Rust">fn is_upside_down( num : u32 ) -> bool {
let numberstring : String = num.to_string( ) ;
let len = numberstring.len( ) ;
let numberstr = numberstring.as_str( ) ;
if numberstr.contains( "0" ) {
return false ;
}
if len % 2 == 1 && numberstr.chars( ).nth( len / 2 ).unwrap( ) != '5' {
return false ;
}
let mut forward : usize = 0 ;
let mut backward : usize = len - 1 ;
while forward <= backward {
let first = numberstr.chars( ).nth( forward ).expect("No digit!").
to_digit( 10 ).unwrap( ) ;
let second = numberstr.chars( ).nth( backward ).expect("No digit!").
to_digit( 10 ).unwrap( ) ;
if first + second != 10 {
return false ;
}
forward += 1 ;
if backward != 0 {
backward -= 1 ;
}
}
true
}
 
fn main() {
let mut solution : Vec<u32> = Vec::new( ) ;
let mut sum : u32 = 0 ;
let mut current : u32 = 0 ;
while sum < 50 {
current += 1 ;
if is_upside_down( current ) {
solution.push( current ) ;
sum += 1 ;
}
}
let five_hundr : u32 ;
while sum != 500 {
current += 1 ;
if is_upside_down( current ) {
sum += 1 ;
}
}
five_hundr = current ;
let five_thous : u32 ;
while sum != 5000 {
current += 1 ;
if is_upside_down( current ) {
sum += 1 ;
}
}
five_thous = current ;
println!("The first 50 upside-down numbers:") ;
println!("{:?}" , solution ) ;
println!("The five hundredth such number : {}" , five_hundr) ;
println!("The five thousandth such number : {}" , five_thous ) ;
}</syntaxhighlight>
{{out}}
<pre>
The first 50 upside-down numbers:
[5, 19, 28, 37, 46, 55, 64, 73, 82, 91, 159, 258, 357, 456, 555, 654, 753, 852, 951, 1199, 1289, 1379, 1469, 1559, 1649, 1739, 1829, 1919, 2198, 2288, 2378, 2468, 2558, 2648, 2738, 2828, 2918, 3197, 3287, 3377, 3467, 3557, 3647, 3737, 3827, 3917, 4196, 4286, 4376, 4466]
The five hundredth such number : 494616
The five thousandth such number : 56546545
</pre>
 
=={{header|Wren}}==
{{trans|Python}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
 
var genUpsideDown = Fiber.new {
15

edits