Advertisement
dmilicev

numbers_divisible_by_all_its_digits.c

Dec 11th, 2019
243
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None
  1. /*
  2.  
  3.     numbers_divisible_by_all_its_digits.c       by Dragan Milicev
  4.  
  5.     Find all positive integers divisible with all of their digits that are non-zero.
  6.  
  7.  
  8.     You can find all my C programs at Dragan Milicev's pastebin:
  9.  
  10.     https://pastebin.com/u/dmilicev
  11.  
  12. */
  13.  
  14. #include <stdio.h>
  15. #include <limits.h>     // for USHRT_MAX = 65535
  16.  
  17.  
  18. // extract digits from number into array digits[]
  19. // returns the number of extracted digits
  20. int extract_digits_from_number( int number, int digits[20] )
  21. {
  22.     int i, j, number_of_digits = 0, mem;
  23.  
  24.     while( number != 0 )
  25.     {
  26.         digits[number_of_digits++] = number % 10;   // fill array digits[]
  27.         number = number / 10;
  28.     }
  29.  
  30.     // reverse first number_of_digits elements of array digits[]
  31.     for ( i=0, j=number_of_digits-1; i<number_of_digits/2; i++, j-- )
  32.     {
  33.         mem = digits[i];
  34.         digits[i] = digits[j];
  35.         digits[j] = mem;
  36.     }
  37.  
  38.     return( number_of_digits );
  39.  
  40. } // extract_digits_from_number
  41.  
  42.  
  43. int main(void)
  44. {
  45.     int number = 12345;     // our number
  46.     int digits[20];         // array to store digits of number
  47.     int number_of_digits=0; // number of digits in number
  48.     int i, j, sum, counter=0;
  49.  
  50.     printf("\n number = %d and it's digits are: \n", number );
  51.  
  52.     number_of_digits = extract_digits_from_number( number, digits );
  53.  
  54.     for ( i=0; i<number_of_digits; i++)
  55.         printf("\n %d \n", digits[i] );
  56.  
  57.     printf("\n number_of_digits = %d \n\n", number_of_digits );
  58.  
  59.     system("PAUSE");
  60.  
  61.     for ( i=1; i<USHRT_MAX; i++)
  62.     {
  63.         number_of_digits = extract_digits_from_number( i, digits );
  64.         sum = 0;
  65.  
  66.         for ( j=0; j<number_of_digits; j++)
  67.         {
  68.             if ( digits[j] != 0 )
  69.             {
  70.                 sum = sum + i%digits[j];
  71.             }
  72.         }
  73.  
  74.         if ( sum == 0 )
  75.         {
  76.             counter++;
  77.             printf("\n %4d. \t %5d \n", counter, i );
  78.         }
  79.     }
  80.  
  81.     printf("\n\n From 1 to %d, there are %d numbers \n\n divisible with all of their digits that are non-zero. \n\n",
  82.             USHRT_MAX, counter );
  83.  
  84.  
  85.     return 0;
  86.  
  87. } // main()
Advertisement
RAW Paste Data Copied
Advertisement