I found this code for the non recursive implementation of towers of Hanoi. But when I compile the program, I get the error: "error C2668: 'pow' : ambiguous call to overloaded function" The compiler points to this line of code --> "int pdisc = int( pow(2,discno));" Could anyone help me fix this? Thanks
//To create Towers of Hanoi using loops
# include <iostream>
# include <math.h>
# define exp (pow(2,i-1)+ double(k)*pow(2,i))
using namespace std;
int main()
{ int discno;
cout << endl << "Enter the number of discs" << endl ;
cin >> discno ;
if (discno<1)
cout << "Sorry ! Enter valid number of discs!!!!!!!!!" << endl << endl ;
else
{ int pdisc = int( pow(2,discno)) ;
int *p = new int [pdisc]; // create an array for no. of steps
for (int i=1; i<= discno; i++)
{ for (int k=0; exp <= pow(2,discno); k++)
{ p[int (exp)] = i ; //get the disc to be moved in each step
}
}
int *poll = new int[discno+1]; //create an array for poll no's w.r.t. disc no's
for (int i=1; i<=discno; i++) poll[i]=1;
if (discno%2==0)
{ for (int i=1; i<=discno ; i++)
{ if (i%2==1) poll[i]=2;
else poll[i]=3;
}
for (int f=1; f<pdisc; f++ )
{ cout << "Step No:" << "\t" << f << ": Move disc no:" << p[f]
<<" to poll no:"<< poll[p[f]] << endl ;
if (p[f]%2==1)
{ poll[p[f]]+=1;
if (poll[p[f]]>3) poll[p[f]]=1;
}
else
{ poll[p[f]]-=1;
if (poll[p[f]]<1) poll[p[f]]=3;
}
}
}
else
{ for (int i=1; i<=discno; i++)
{ if (i%2==1) poll[i]=3;
else poll[i]=2;
}
for (int f=1; f<pdisc; f++)
{ cout << "Step No:" << "\t" << f <<": Move disc no:"<< p[f]
<<" to poll no:" <<poll[p[f]]
<< endl ;
if (p[f]%2==1)
{ poll[p[f]]-=1;
if (poll[p[f]]<1) poll[p[f]]=3;
}
else
{ poll[p[f]]+=1;
if (poll[p[f]]>3) poll[p[f]]=1;
}
}
}
cout << endl ;
}
return 0;
}
1) pow() doesn't take 2 ints. It takes floats, doubles or long doubles. When you give the compiler two ints, it doesn't know if you want to call the float version or the double version or what.
The trick is to give it at least one floating point value. ie: pow(2.0,discno). Because 2.0 is a double, it will know to call the double version of pow.
2) You don't need to (and shouldn't) call pow to raise 2 to an integer power. Bitshifting is much better
1 2 3
int foo = pow(2,x);
// the above is just a very slow and inefficient way to do this:
int foo = 1 << x;