home *** CD-ROM | disk | FTP | other *** search
/ DP Tool Club 15 / CD_ASCQ_15_070894.iso / vrac / tpchal_1.zip / DD_2.C < prev    next >
C/C++ Source or Header  |  1994-05-26  |  2KB  |  64 lines

  1. /*
  2.  * Function to find the "magic" 9 digit number, where every substring
  3.  * of the number (to the left) is divisible by the number of digits in
  4.  * that substring. Non-recursive version.
  5.  *
  6.  * Dave Dunfield - May 20, 1994 - Released to the Public Domain
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include <string.h>
  11.  
  12. main()
  13. {
  14.       long num, next;
  15.       char digits[10];
  16.       char lastdig[10];
  17.       int i, n
  18. #ifdef TEST
  19.       , I;
  20.  
  21.       for (I = 0; I < 1000; ++I)
  22.       {
  23. #else
  24.       ;
  25. #endif
  26.       n = 1;
  27.       num = 0L;
  28.       memset(digits, 0, sizeof(digits));
  29.       memset(lastdig, 0, sizeof(lastdig));
  30.  
  31.       do
  32.       {
  33. next:
  34.             if(n >= 10)                    /* This number qualifies */
  35.             {
  36. #ifdef TEST
  37.             if (999 == I)
  38. #endif
  39.                 printf("Number = %ld\n", num);
  40.             break;
  41.             }
  42.             else for(i=lastdig[n]+1; i<10; ++i) /* Test digits 1-9 only  */
  43.             {
  44.                   if(digits[i])                 /* Digit in use          */
  45.                         continue;
  46.                   if(!((next = num*10 + i) % n))/* Divides - proceed     */
  47.                   {
  48.                         digits[i] = (char)-1;   /* Mark digit as used    */
  49.                         num = next;             /* Proceed from here     */
  50.                         lastdig[n++] = i;       /* Save continuation     */
  51.                         goto next;              /* Restart test          */
  52.                   }
  53.             }
  54.             digits[num % 10] = 0;               /* Release digit         */
  55.             num /= 10;                          /* Remove last attempt   */
  56.             lastdig[n] = 0;                     /* Reset lower starts    */
  57.       }
  58.       while(--n);
  59. #ifdef TEST
  60.       }
  61. #endif
  62.       return 0;
  63. }
  64.