function y = pages(n) % This function will convert n pages to digits. % In a "function" statement, the "y" is just a dummy output % variable, but, unfortunately, we must put something there! % The input variable is clearly "n". % We must name this file: Pages.m % When we execute it (from the workspace), we simply type: % Pages(12) [in the Command Window!] % % Example: If n = 12, then the first 9 pages will have one digit % (9 digits so far), and then the remaining 3 pages will have two % digits (6 more digits), for a total of 15 digits used to number % the pages. % % We start with one (level one) digit pages. We haven't processed % any pages yet, so digits = 0, for now. level = 1; digits = 0; % We *only* execute the statements between the "while" and the "end" % when there are "too many" pages to process. That is, if the % remaining number of pages is greater than the max. number of pages % at a particular level, then do the stated processing! while (n > 0.9*10^level) % We process an entire level! % Remember? It was 9 digits for the first level, % 90 digits for the second, 900 for the third, etc. % We *subtract* off the number of pages we plan to process % during this iteration. n = n - 0.9*10^level; % Add the number of digits for this level. digits = digits + level*(0.9*10^level); % Increment the level number for the next pass. level = level + 1; end % We now process the "leftover" pages. Each page has (level) digits. digits = digits + level*n; % Print out the answer! fprintf('We used %6d digits!\n',digits);