A14 Answer


#include <stdio.h>
#include <stdlib.h>

/* Puzzle A14 -- on each line k print all the integers in the
|  range 100*k to (100*k+99) that are multiples of 23.
|
|  Not a very good solution: does 23 times more work than
|  is needed.
*/
int main(int argc, char *argv[])
{
  int k;     /* line number */
  int base;  /* The base number for line k is 100*k */
  int j;     /* These values 0..99 are added to the */
             /* base number for line k. */
  
  for (k=0; k<12; k++)
  {
    base = 100*k;
    for ( j=0; j<100; j++ )
      if ( (base+j)%23 == 0 )
        printf("%7d", (base+j) );
    printf("\n");
  }
  
  system("PAUSE");	
  return 0;
}

Comments: This solution works by first generating line numbers k=0, 1, 2, ..., 11 and then using the inner loop to generate 100 integers starting with k*100. Each integer is tested, and printed out if 23 divides it evenly. But all integers are generated, one-by-one, not just multiples of 23, so this program does 23 times more work than is needed.

Another way to approach this problem is to generate only integers that are multiples of 23: 0, 23, 46, 69, 92, 115, ... and so on. Test each integer to see if it belongs on the current line before printing it. Print a newline character when the current integer should go on the next line.

If your program used that approach, congratulations! If not, try writing another program before looking at the improved solution, below.


int main(int argc, char *argv[])
{
  int j;     /* the current integer */
  int k;     /* the current line number */
  int line;  /* the line the current integer belongs on */

  int maxLine = 11 ; /* number of lines to print */
  
  k = 0;
  
  /* generate multiples of 23 */
  for ( j=0; j<= maxLine*100+99; j+=23 )
  {
    /* find the line number using integer division */
    line = j/100 ; 
    
    /* does the number belong on the current line? */
    if ( line == k+1 )
    {
      printf("\n%5d ", j);
      k++ ;
    }
    else
      printf("%5d ", j );
  }
  printf("\n");
  
  system("PAUSE");	
  return 0;
}