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.

Thursday, April 06, 2006

A small puzzle!

Hey guys! Back to ma English blog.

Goin thru some books to post somethin technical! Meanwhile i'll jus ask a small puzzle for you guys to solve. Its very simple. Try writing a C program printing 2147483647 0s(zeros). Try making it as efficient as possible. Also try to make the code as little as possible.

Hope you guys try it out!

I'll come up with a different answer for the above question if possible. Its very simple. Try incrementally.

All the very best to all of you!