Narcissistic decimal number: Difference between revisions
Content added Content deleted
m (→{{header|REXX}}: changed the wording on a comment to reflect the statement.) |
m (→{{header|REXX}}: added REXX section header comments.) |
||
Line 178: | Line 178: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
This is an idiomatic approach. |
|||
===version 1=== |
===version 1=== |
||
<lang rexx>/*REXX program to generate and display a number of narcissistic numbers.*/ |
<lang rexx>/*REXX program to generate and display a number of narcissistic numbers.*/ |
||
Line 186: | Line 187: | ||
do j=1 until #==N; L=length(j) /*get the length of the J number.*/ |
do j=1 until #==N; L=length(j) /*get the length of the J number.*/ |
||
s=left(j,1)**L /*1st digit in J raised to L pow.*/ |
s=left(j,1)**L /*1st digit in J raised to L pow.*/ |
||
⚫ | |||
do k=2 for L-1 /*perform for each digit in J. */ |
do k=2 for L-1 /*perform for each digit in J. */ |
||
s=s+substr(j,k,1)**L /*add digit raised to pow to sum.*/ |
s=s+substr(j,k,1)**L /*add digit raised to pow to sum.*/ |
||
if s>j then iterate j /*perform a short-circuit test. */ |
if s>j then iterate j /*perform a short-circuit test. */ |
||
end /*k*/ /* [↑] calculate the rest of sum*/ |
end /*k*/ /* [↑] calculate the rest of sum*/ |
||
⚫ | |||
if s\==j then iterate /*does sum equal to J? No ∙∙∙ */ |
if s\==j then iterate /*does sum equal to J? No ∙∙∙ */ |
||
#=#+1 /*bump the narcissistic num count*/ |
#=#+1 /*bump the narcissistic num count*/ |
||
Line 225: | Line 224: | ||
25 narcissistic: 24678050 |
25 narcissistic: 24678050 |
||
</pre> |
</pre> |
||
===version 2=== |
|||
This REXX version is optimized to pre-compute all the ten (single) digits raised to all possible powers (which is 39). |
|||
<lang rexx>/*REXX program to generate and display a number of narcissistic numbers.*/ |
|||
numeric digits 39 /*be able to handle the largest #*/ |
|||
parse arg N .; if N=='' then N=25 /*get number of narcissistic #'s.*/ |
|||
N=min(N,89) /*there are 89 narcissistic #s.*/ |
|||
do w=1 for 39 /*generate tables: digits ^ L pow*/ |
|||
do i=0 for 10; @.w.i=i**w; end /*build table of 10 digs ^ L pow.*/ |
|||
end /*w*/ /* [↑] table is of a fixed size.*/ |
|||
#=0 /*number of narcissistic # so far*/ |
|||
do j=1 until #==N; L=length(j) /*get the length of the J number.*/ |
|||
s=0 /*sum of the J digs ^ L (so far)*/ |
|||
do k=1 for L /*perform for each digit in J. */ |
|||
_=substr(j,k,1) /*select a single digit to sum. */ |
|||
s=s+@.L._ /*add digit raised to pow to sum.*/ |
|||
if s>j then iterate j /*perform a short-circuit test. */ |
|||
⚫ | |||
if s\==j then iterate /*does sum equal to J? No ∙∙∙ */ |
|||
#=#+1 /*bump the narcissistic num count*/ |
|||
say right(#,9) ' narcissistic:' j /*display index & narcissistic #.*/ |
|||
end /*j*/ /* [↑] this list starts at 1. */ |
|||
⚫ | |||
'''output''' is the same as REXX version 1. |
|||
<br> |