LeetCode 483: Smallest Good Base Solution

Master LeetCode problem 483 (Smallest Good Base), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

483. Smallest Good Base

Problem Explanation

Explanation

To find the smallest good base for a given number n, we can iterate through all possible values of the base from 2 to n-1. For each base k, we can calculate the geometric progression sum using the formula (k^m - 1) / (k - 1), where m is the number of digits in the base k representation of n.

We can use binary search to find the optimal value for m, as the number of digits in the base k representation of n will be in the range [2, log2(n)]. By iterating through possible values of m, we can find the smallest good base for n.

Solution Code

class Solution {
    public String smallestGoodBase(String n) {
        long num = Long.parseLong(n);
        for (int m = (int)(Math.log(num + 1) / Math.log(2)); m > 2; m--) {
            long l = 2, r = (long)Math.pow(num, 1.0 / (m - 1)) + 1;
            while (l < r) {
                long k = l + (r - l) / 2;
                long sum = 0;
                for (int i = 0; i < m; i++) {
                    sum = sum * k + 1;
                }
                if (sum == num) {
                    return String.valueOf(k);
                } else if (sum < num) {
                    l = k + 1;
                } else {
                    r = k;
                }
            }
        }
        return String.valueOf(num - 1);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 483 (Smallest Good Base)?

This page provides optimized solutions for LeetCode problem 483 (Smallest Good Base) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 483 (Smallest Good Base)?

The time complexity for LeetCode 483 (Smallest Good Base) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 483 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 483 in Java, C++, or Python.

Back to LeetCode Solutions