Narcissistic decimal number: Difference between revisions

→‎{{header|R}}: While loop solution
(Added Wren)
(→‎{{header|R}}: While loop solution)
Line 3,375:
 
=={{header|R}}==
===For loop solution===
This is a slow method and it needed above 5 minutes on a i3 machine.
<lang R>for (u in 1:10000000) {
Line 3,387 ⟶ 3,388:
}
if (sum(control) == u) print(u)
}</lang>
</lang>
{{out}}
<pre>
Line 3,414:
[1] 4210818
[1] 9800817
[1] 9926315</pre>
===While loop solution===
</pre>
As with the previous solution, this is rather slow. Regardless, we have made the following improvements:
*This solution allows us to control how many Armstrong numbers we generate.
*Rather than using a for loop that assumes that we will be done by the 10000000th case, we use a while loop.
*Rather than using nchar, which misbehaves if the inputs are large enough for R to default to scientific notation, we use format.
*We exploit many of R's vectorized functions, letting us avoid using any for loops.
*As we are using format anyway, we take the chance to make the output look nicer.
<lang R>generateArmstrong<-function(howMany)
{
resultCount<-i<-0
while(resultCount<howMany)
{
#The next line looks terrible, but I know of no better way to convert a large integer in to its digits in R.
digits<-as.integer(unlist(strsplit(format(i,scientific = FALSE),"")))
if(i==sum(digits^(length(digits))))
{
cat("Armstrong number ",resultCount<-resultCount+1,": ",format(i, big.mark = ","),"\n",sep="")
}
i<-i+1
}
generateArmstrong(25)</lang>
{{out}}
<pre>Armstrong number 1: 0
Armstrong number 2: 1
Armstrong number 3: 2
Armstrong number 4: 3
Armstrong number 5: 4
Armstrong number 6: 5
Armstrong number 7: 6
Armstrong number 8: 7
Armstrong number 9: 8
Armstrong number 10: 9
Armstrong number 11: 153
Armstrong number 12: 370
Armstrong number 13: 371
Armstrong number 14: 407
Armstrong number 15: 1,634
Armstrong number 16: 8,208
Armstrong number 17: 9,474
Armstrong number 18: 54,748
Armstrong number 19: 92,727
Armstrong number 20: 93,084
Armstrong number 21: 548,834
Armstrong number 22: 1,741,725
Armstrong number 23: 4,210,818
Armstrong number 24: 9,800,817
Armstrong number 25: 9,926,315</pre>
 
=={{header|Racket}}==
331

edits