Programming Puzzle 27 - So, what's the page count?

Puzzle 27

It takes 1629 digits to number the pages of a book. How many pages does the book have?

You may assume the first page is numbered "1".

Write an xbasic script to solve the puzzle. You may display your result in a message box on screen, or you may write the result to the trace window.

Have fun !

Credit: Basic-mathematics.com for the puzzle.

Re: Programming Puzzle 27 - So, what's the page count?

No takers? I'm sure someone will find a more efficient way, but this works:

Code:

`dim charct as n = 0`

dim pageno as n = 0

while 1=1

pageno = pageno + 1

charct = charct + len("" + pageno)

if charct >= 1629

exit while

end if

end while

msgbox("Number of pages in the book", "" + pageno)

Re: Programming Puzzle 27 - So, what's the page count?

Steve, that's right!

I showed your solution to the "professor" and he was impressed. While mumbling about students who do well even though they "hang out" at the back of the class, he found two aspects of your solution noteworthy.

a) The key to this puzzle is controlling the while .. end while code block. Your solution begins a loop that will never end because 1 is always equal to 1, but then, cleverly, exits when the desired condition is observed. A neat trick, that will be useful to many.

b) To determine the number of characters in a numeric page number one must convert the numeric value to a character string. Many would use the STR() function, which results in leading blank spaces that must be trimmed before the length is determined. Your use the concatenation operator ( "+" ) neatly bypasses that complexity. By concatenating the null string with the page number, the operator will automatically convert the numeric to character data, and does so WITHOUT prepending blank spaces a la STR(). Readers may want to consult the docs, here, for details.

Move to the head of the class.

1 Attachment(s)

Re: Programming Puzzle 27 - So, what's the page count?

/cough 3rd time is the charm :grin:

( course that is if I ignore attempts 2-5 )

Re: Programming Puzzle 27 - So, what's the page count?

Andy,

The "professor" appreciates your tenacity. He agrees, "if at first you don't succeed, try, try again." And, this time, you got it.

Nice use of the convert_type() function to convert your "numeric" page number into a "character" string so that its length (number of digits) could be determined.

Good work.