I’m trying to solve a problem which asks to find all squares of 1 <= N <= 300 that are palindromic when expressed in base B. I’ve got my solution however, it’s way too slow and what is slowing it down is my solution to converting a number to base B.
long around(long n)
{
long around = 0;
while (n > 0){
around = around * 10 + (n % 10);
n = n / 10;
}
return around;
}
long convert(int n, int b)
{
long x = 0;
while (true){
x = x * 10 + (n % b);
if (n == 1)
break;
n = n / b;
}
return around(x);
}
Please recommend any faster solutions to converting decimal to base B or give any tips to improve my current solutions performance.
The problem is your
convertfunction, which runs into an infinite loop. You are only breaking whenn == 1, but what if it never becomes 1?Consider
n = 4andb = 5. Then4 / 5will be0. Oncenis zero, it will always be zero, and never1.You should break out of the loop when
n < b.