Marijus
Marijus

Reputation: 4365

convert decimal to base x

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.

Upvotes: 2

Views: 756

Answers (1)

IVlad
IVlad

Reputation: 43477

The problem is your convert function, which runs into an infinite loop. You are only breaking when n == 1, but what if it never becomes 1?

Consider n = 4 and b = 5. Then 4 / 5 will be 0. Once n is zero, it will always be zero, and never 1.

You should break out of the loop when n < b.

Upvotes: 2

Related Questions