COME ON CODE ON

A blog about programming and more programming.

Tower of Hanoi

with 3 comments

This is a C program to solve the very famous Tower of Hanoi problem. It neither uses recursion nor stack. Moreover, it solves the problem in just 6 statements. See the indenting done to make it look like a tower.

main(
){int
z,y,n
;scanf("%d",&n);
for(y=1;(1<<n)-y
;y<<=z-1,printf(
"Move disk %i from %i to %i.\n"
,z,(y&y-1)%3+1,((y|y-1)+1)%3)+1,y
++)for(z=1;!(y&1);z++,y>>=1);}/****/

Found it while googling.

-fR0D

Advertisements

Written by fR0DDY

February 10, 2009 at 9:31 AM

Posted in Beautiful Codes

Tagged with ,

3 Responses

Subscribe to comments with RSS.

  1. Xcellent one bhaiya….it’s awesome

    Saket

    February 13, 2009 at 10:47 AM

  2. the output is wrong for large inputs ??

    Indian

    March 18, 2009 at 9:10 AM

  3. Shouldn’t the last ‘+1’ (before y) in last 2nd line be inside the bracket?

    sidd

    October 17, 2010 at 9:22 AM


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: