THE PUZZLET PAGE

PUZZLET 075 - THE SOLUTION


' Puzzlet #075
' Write down successive integers from 1 upwards.
' When will the number of times the digit "1"
' has been written down equal the last number
' to have been written down? The trivial result
' of writing just "1" down can be ignored.
' By Dave Ellis.

declare CountOnes(c: int)
def count, it: int
openconsole
print "Counting ...": print
it = 1
count = 1

do
    it = it + 1
    count = count + CountOnes(it)
until count = it

print "Writing down all the integers from "
print "1 to ", it, " inclusive involves "
print "writing the digit '1' ", it, " times."
print: print "Press any key to exit ..."
do: until inkey$ <> ""
closeconsole
end

sub CountOnes(c)
def c$: string
def nrOnes, i, L: int
c$ = ltrim$(str$(c))
L = len(c$)
nrOnes = 0
for i = 1 to L
    if mid$(c$, i, 1) = "1"
        nrOnes = nrOnes + 1
    endif
next i
return nrOnes
   
   
PROGRAM NOTES


Variable it is used to keep track of the "written down" numbers.  The variable count holds the number of times the digit 1 has been used in the "written down" numbers.

The main program is the very short DO loop.  It increments it, then adds the number of 1's in it's new value to the totaliser count. The loop is re-executed until the number of 1's in count is equal to the latest value of it.

Function CountOnes() does all the hard work. It uses variable i to iterate through a string representation of it, held in c$. This iteration continues to the end of c$, denoted by variable Lc$ itself).

Every time a "1" character is encountered in c$, it's totalised in variable nrOnes. When all characters have been examined, the value in nrOnes is returned to the calling routine.
(derived form the length of

When the program is run, it generates the inset screen.  The answer is a much larger value than might be guessed at.

Counting ...

Writing down all the integers from
1 to 199981  inclusive involves
writing the digit '1' 199981  times.

Press any key to exit ...





Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.