Monday, April 10, 2006

The answer for the puzzle asked in the last post.

Hey!

Back with the answer.

Lets move step by step towards the final answer. Incremental improvement towards the solution.

Lets assume that we dont have any knowlegde in C other than a hello World program. Such a person would attack the problem as

#include

int main()
{
printf( "0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 ........" );

return 0;

}

This however is not a solution. Not at all.

Moving onto the next step, lets assume that we know the conditionals and loops exixting in C. Not more than that. Then we might use a loop to print the required thing.

#include

int main()
{
int x = 2147483647;

for( int i = 0; i < x; i++ )
printf( "0" );

return 0;
}

We might reduce the number of iterations by printing more number of zeros in the printf.

Now lets move to my solution which is quite small compared to the above solutions. I won't tell that mine is the efficient one. Who knows there might be other efficient ways.

If you look at the documentation of printf. ( You can man it on a Linux box,just say $ man 3 printf ). I'm not gonna print the documentation. Go thru it if you are interested. This was the solution i got.

#include

int main()
{
int x = 2147483647, y = 0;
printf("%0*d", x, y );

return 0;
}

The logic goes like this. * in the printf would take the corresponding argument passed as the argument and print those many 0's. the d option would add the next argument to the existing number ( those many number of zeros ) and print it. As we want only zeros to get printed, we pass 0 as the second argument. If you fail to pass a second argument, it would take some garbage value.

Hope that this is a better solution. Pour in your implementations if it is more efficient.

Kudos to the creators of C. Dennis M. Ritchie and Brian W. Kernighan.

Right now, tryin to solve a problem which i got thru a mailing list. Quite interesting. Will post it once i solve it.

Bye.

4 Comments:

Blogger Sandesh said...

Sorry that i dint escape the include files. please include stdio.h in the above written programs.

6:50 AM  
Anonymous donald said...

Honestly speakin, i had thought of the 2nd method, but was not sure if it was the answer cuz u come up with hi fi stuff.. anyways ur implementation is good and efficient i guess....

7:45 AM  
Blogger Sandesh said...

Thanks for the comments maga!

8:01 AM  
Blogger nanuseena said...

eeg goththaytha est kasta antha eradu blog maintain maadodhu antha..

9:15 PM  

Post a Comment

<< Home