Sunday, June 12, 2011

Ugly Numbers


Hey guys, As I promised you few posts ago,
here is my solution for the Ugly numbers question:


#include<stdio.h>
void getUglyNumbersBruteForce(long num )
{
long i,count;
count=0;
long backup;
i=2;

while (count < num )
 {
  backup=i;
  while (i%5==0)i=i/5;
  while (i%3==0)i=i/3;
  while (i%2==0)i=i/2;

  if (i==1)
  {
    printf("%d)The number is: %d\n",count,backup);
    count++;
  }
  i=backup;
  i++;
 }

}

long min3(long num1,long num2,long num3)
{
if ((num1 < num2 ) && (num1 < num3 )) return num1;
if ((num2 < num3 ) && (num2 < num3 )) return num2;
if ((num3 < num2 ) && (num3 < num1 )) return num3;

}

int GetUglyNumbersDynamicProgramming(int num)
{
   long arrayUgly[num];
   long nextNumber,Next2,Next3,Next5;
   int ptrNext2=0;
   int ptrNext3=0;
   int ptrNext5=0;
   int i;
   arrayUgly[0]=1;
   Next2=arrayUgly[0]*2;
   Next3=arrayUgly[0]*3;
   Next5=arrayUgly[0]*5;

   for (i=1;i < num ; i++)
   {
       nextNumber=min3(Next2,Next3,Next5);
       arrayUgly[i]=nextNumber;

       if (nextNumber==Next2)
       {
           ptrNext2++;
           Next2=arrayUgly[ptrNext2]*2;
       }
       if (nextNumber==Next3)
       {
           ptrNext3++;
           Next3=arrayUgly[ptrNext3]*3;
       }
       if (nextNumber==Next5)
       {
           ptrNext5++;
           Next5=arrayUgly[ptrNext5]*5;
       }

       printf("%d)The number is: %d\n",i,arrayUgly[i]);
   }

}

int main()
{

   GetUglyNumbersDynamicProgramming(1500);
   printf("\n\n\n\n\n");
   getUglyNumbersBruteForce(1500);
   return 0;
}

No comments:

Post a Comment

About