Happy numbers: Difference between revisions

(consolidate BASICs)
(→‎{{header|Commodore BASIC}}: Add implementation.)
Line 1,064:
28 is a happy number
31 is a happy number</pre>
 
==={{header|Commodore BASIC}}===
The array sizes here are tuned to the minimum values required to find the first 8 happy numbers in numerical order. The <tt>H</tt> and <tt>U</tt> arrays are used for memoization, so the subscripts <tt>H(</tt><i>N</i><tt>)</tt> and <tt>U(</tt><i>N</i><tt>)</tt> must exist for the highest <i>N</i> considered. The array <tt>N</tt> must have room to hold the longest chain examined in the course of determining whether a single number is happy, which thanks to the memoization is only ten elements long.
 
<syntaxhighlight lang="gwbasic">
100 C=8:DIM H(145),U(145),N(9)
110 PRINT CHR$(147):PRINT "THE FIRST"C"HAPPY NUMBERS:":PRINT
120 H(1)=1:N=1
130 FOR C=C TO 0 STEP 0
140 : GOSUB 200
150 : IF H THEN PRINT N,:C=C-1
160 : N=N+1
170 NEXT C
180 PRINT
190 END
200 K=0:N(K)=N
210 IF H(N(K)) THEN H=1:FOR J=0 TO K:U(N(J))=0:H(N(J))=1:NEXT J:RETURN
220 IF U(N(K)) THEN H=0:RETURN
230 U(N(K))=1
240 N$=MID$(STR$(N(K)),2)
250 L=LEN(N$)
260 K=K+1:N(K)=0
270 FOR I=1 TO L
280 : D = VAL(MID$(N$,I,1))
290 : N(K) = N(K) + D * D
300 NEXT I
310 GOTO 210</syntaxhighlight>
 
{{Out}}
<pre>
THE FIRST 8 HAPPY NUMBERS:
 
1 7 10 13
19 23 28 31
 
 
READY.
</pre>
 
==={{header|FreeBASIC}}===
1,480

edits