## QB64: Wondrous Numbers.

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!

Moderators: Pete, Mods

Jack002
Newbie
Posts: 5
Joined: Wed Jul 10, 2013 1:28 pm

### QB64: Wondrous Numbers.

This is not a question, just an observation with a number game/function.

If you have read Godel Escher Bach, you would know what a Wondrous number is.

This site defines it nicely
http://mathforum.org/library/drmath/view/57184.html

Start with an arbitrary natural number (integer greater than zero). If the number is even, divide it by 2. If it is odd, multiply by 3 and add 1. Repeat until you come out with 1. A number is wondrous if and only if it eventually reaches 1 through this process

Now the site thinks you need pencil and paper to determine if a number is one or not. I have a computer. I'll make it do the work.

Here's the program I wrote back a few years ago. (Pardon my lack of new QB64 commands, we have a better basic now)

Code: Select all

``````DECLARE FUNCTION get.a.key\$ ()
DECLARE SUB pause ()
DECLARE FUNCTION w2! (a!)
DECLARE FUNCTION wonderous! (a!)

CLS

PRINT "Wonderous numbers - what ones are?"
PRINT

qq = 1

WHILE 0 = 0

FOR a = 1 TO 40
r = INT(RND * 1000000)
PRINT "W("; r; ") = "; w2(r)
NEXT
pause

WEND

FOR t = 1 TO 10000
FOR a = qq TO qq + 39
PRINT "W("; a; ") = "; w2(a)
NEXT
pause
qq = qq + 40
NEXT

FUNCTION get.a.key\$

temp\$ = INKEY\$
WHILE temp\$ = ""
temp\$ = INKEY\$
WEND
get.a.key\$ = temp\$

END FUNCTION

SUB pause

PRINT
PRINT "<press any key>"
aa\$ = get.a.key\$

END SUB

FUNCTION w2 (a)
'inputs a, returns 1 if wonderous, not recursive

a1 = a 'temp var to use

WHILE a1 > 1
IF a1 = 1 THEN w2 = 1: EXIT FUNCTION

IF a1 < 1 OR INT(a1) <> a1 THEN PRINT "ERROR "; a: STOP

IF a1 / 2 = INT(a1 / 2) THEN
a1 = a1 / 2
ELSE
a1 = 3 * a1 + 1
END IF
'PRINT a1;
WEND

w2 = a1

END FUNCTION

FUNCTION wonderous (a)

IF a = 1 THEN wonderous = 1: EXIT FUNCTION

IF a < 1 THEN PRINT "ERROR "; a: STOP

IF a / 2 = INT(a / 2) THEN
'PRINT "even": STOP
'PRINT a / 2
wonderous = wonderous(a / 2)
ELSE
'PRINT "odd": STOP
wonderous = wonderous(3 * a + 1)
END IF

END FUNCTION
``````
Note the two functions. One is recursive, one is not. I'd be careful with the recursive one, you don't know how many steps it will take and the stack is vulnerable.

Anyone here into strange or useless functions?

Jack T.