I am trying to convert this recursive algorithm
isqrt(n){
if(n==0){
return 0;
}
a = 2*isqrt(n/4)+1;
if(n<(a*a)){
return a-1;
} else {
return a;
}
}
into an iterative algorithm. So far I was able to do this:
isqrt(n){
vector c;
for(d = n; d>0; d = d/4){
c.push_back(d);
}
res = 0;
for(con = c.size(); con>0; con = con-1){
a = 2*res+1;
if(c[con-1]<(a*a)){
res = a-1;
} else {
res = a;
}
}
return res;
}
This could be a solution to my problem, but my approach was simply "simulating the function stack" inside the function itself with the vector, which works but still runs in O(floor(log4(n))) space, which in my use case is greatly undesirable. Is there any way to modify this algorithm in an iterative algorithm that runs in O(1) space? If possible the time complexity should remain the same.