Anonymous user
Narcissistic decimal number: Difference between revisions
→{{header|REXX}}: changed/added whitespace and comments, improved speed of the 3rd REXX pgm by using PARSE instead of SUBSTR for extracting decimal digits of a number.
m (added a note about Armstrong numbers.) |
(→{{header|REXX}}: changed/added whitespace and comments, improved speed of the 3rd REXX pgm by using PARSE instead of SUBSTR for extracting decimal digits of a number.) |
||
Line 1,801:
=={{header|REXX}}==
===
<lang rexx>/*REXX
numeric digits 39 /*be able to handle
parse arg N .; if N=='' then N=25 /*
N=min(N,89) /*there are only 89 narcissistic #s. */
#=0 /*number of narcissistic
do j=0 until #==N; L=length(j) /*get
do k=2 for L-1 until
end /*k*/ /* [↑] calculate the rest of the sum. */
if
#=#+1 /*bump
say right(#,9) ' narcissistic:' j /*display index
end /*j*/ /* [↑] this list starts at 0
/*stick a fork in it, we're all done. */</lang>
'''output''' when using the default input:
<pre>
Line 1,848:
===optimized===
This REXX version is optimized to pre-compute all the ten (single) digits raised to all possible powers (which is 39).
<lang rexx>/*REXX
numeric digits 39 /*be able to handle
parse arg N .; if N=='' then N=25
N=min(N,89) /*there are only 89 narcissistic #s. */
do w=1 for 39 /*generate tables: digits ^ L
do i=0 for 10; @.w.i=i**w; end /*build table of
end /*w*/ /* [↑] table is
#=0 /*number of narcissistic
do j=0 until #==N; L=length(j) /*get
_=left(j,1) /*select the first decimal digit to sum
do k=2 for L-1 until
_=substr(j,k,1) /*select the next decimal digit to sum.
end /*k*/ /* [↑] calculate the rest of the sum. */
if
#=#+1 /*bump
say right(#,9) ' narcissistic:' j /*display index
end /*j*/ /* [↑] this list starts at 0
/*stick a fork in it, we're all done. */</lang>
'''output''' is the same as 1st REXX version.
Line 1,873:
This REXX version is optimized by unrolling part of the DO loop that sums the digits.
<br>The unrolling also necessitated the special handling of one- and two-digit narcissistic numbers.
<lang rexx>/*REXX
numeric digits 39 /*be able to handle
parse arg N .; if N=='' then N=25
N=min(N,89) /*there are only 89 narcissistic #s. */
do w=1 for 39 /*generate tables: digits ^ L
do i=0 for 10; @.w.i=i**w; end /*build table of
end /*w*/ /* [↑] table is
#=0 /*number of narcissistic
do low=0 for 10; call tell low; end /*handle the
/* [↓] skip the
do j=100; L=length(j)
parse var m _ +1 m
$=$ + @.L._
end
if $==j then call tell j
exit
/*──────────────────────────────────TELL
exit /*stick a fork in it, we're done.*/▼
tell: #=#+1 /*bump the counter for narcissistic #s.*/
▲/*──────────────────────────────────TELL subroutine─────────────────────*/
▲tell: parse arg y /*get narcissistic # to display. */
if #=
▲say right(#,9) ' narcissistic:' y /*display index & narcissistic #.*/
'''output''' is the same as 1st REXX version.
|