Computer Programming Contest Preparation

ToolBox - Source for: 1/136/a.c



/home/toolbox/public_html/solutions/1/136/a.c
    1 #include <stdio.h>
    2 #include <string.h>
    3 #include <sys/types.h>
    4 #include <sys/stat.h>
    5 #include <fcntl.h>
    6 #include <stdint.h>
    7 #include <math.h>
    8 #include <stdlib.h>
    9 
   10 #define TRUE  (1 == 1)
   11 #define FALSE (1 != 1)
   12 
   13 #define DEBUG if (FALSE)
   14 
   15 
   16 /*
   17  *  Author: Isaac Traxler
   18  *    Date: 2022-02-25
   19  * Purpose: fun
   20  * Problem: 136 - Ugly Numbers
   21  */
   22 
   23 /*
   24  * This template reads data until a terminating value is reached.
   25  */
   26 
   27 /*
   28  * Usinf DP algorithm from: https://www.geeksforgeeks.org/ugly-numbers/
   29  */
   30 #define UMAX 1504
   31 
   32 int ugly[UMAX];
   33 
   34 int minOf(int a, int b, int c)
   35 {
   36     /* FUNCTION minOf */
   37     int toReturn;
   38 
   39     if ( a < b)
   40         if (a < c)
   41             toReturn = a;
   42         else
   43             toReturn = c;
   44     else if (b < c)
   45         toReturn = b;
   46     else
   47         toReturn = c;
   48     return toReturn;
   49 } /* FUNCTION minOf */
   50 
   51 void init()
   52 {
   53     /* FUNCTION init */
   54     int c2;
   55     int c3;
   56     int c5;
   57     int n2;
   58     int n3;
   59     int n5;
   60     int i;
   61 
   62     ugly[0] = 1;
   63     c2 = 0;
   64     c3 = 0;
   65     c5 = 0;
   66 
   67     for (i=1; UMAX>i; i++)
   68         {
   69             /* fill it up */
   70             n2 = ugly[c2] * 2;
   71             n3 = ugly[c3] * 3;
   72             n5 = ugly[c5] * 5;
   73             ugly[i] = minOf(n2, n3, n5);
   74 
   75             if (n2 == ugly[i])
   76                 {
   77                     /* found next number */
   78                     c2++;
   79                     n2 = ugly[c2] * 2;
   80                 } /* found next number */
   81             if (n3 == ugly[i])
   82                 {
   83                     /* found next number */
   84                     c3++;
   85                     n3 = ugly[c3] * 3;
   86                 } /* found next number */
   87             if (n5 == ugly[i])
   88                 {
   89                     /* found next number */
   90                     c5++;
   91                     n5 = ugly[c5] * 5;
   92                 } /* found next number */
   93 
   94             DEBUG printf("ugly[%d] = %d\n", i, ugly[i]);
   95         } /* fill it up */
   96 } /* FUNCTION init */
   97 
   98 
   99 void process()
  100 {
  101     /* FUNCTION process */
  102 
  103     printf("The 1500'th ugly number is %d.\n", ugly[1499]);
  104 } /* FUNCTION process */
  105 
  106 int main ()
  107 {
  108     /* main */
  109     init();
  110     process();
  111     return EXIT_SUCCESS;
  112 } /* main */
  113