Re: [C] need help with programming exercise

From: Elliot Marks (emarks_at_email.net)
Date: 03/02/04


Date: Tue, 02 Mar 2004 15:21:47 GMT

Francis Glassborow wrote:

>>> #include <stdio.h>
>>> #include <stdlib.h>
>>> int ugly(int i){
>>> while((i % 2) == 0)i /= 2;
>>> while((i % 3) == 0)i /= 3;
>>> while((i % 5) == 0)i /= 5;
>>> return (i == 1);
>>> }
>>> int main(){
>>> int start = 1;
>>> int end = 100;
>>> int i;
>>> for(i = start; i != end; ++i){
>>> if(ugly(i)) printf("%d\n", i);
>>> }
>>> }
>>> The real art of programming is not the ability to write code, but the
>>> decision as to how code should express a solution to a problem. That is
>>> the really difficult part, and the part that is very hard to teach.
>>
>>
>> Thanks, for the correction of my code and your much more elegant
>> solution. I understand why it works, but would never have thought of
>> doing it this way.
>
>
> But learning to think that way is what learning to program is really
> about. And yes, it does take many years of practice until one can do it
> on the fly.

I was so impressed by the simple elegance of ugly() that it took
me a while to realize it doesn't produce the correct output. It
outputs 1, 2, 3 and 5 as ugly numbers and they, of course, are
not. Adding the line:

      if(i==1||i==2||i==3||i==5) return 0;

at the top of the function diminishes its elegance somewhat but
improves the result. Thanks again to Francis for his help.