简体   繁体   中英

Calculate log base 2 recursion

i'm creating recursion method that calculate Log base 2. for log*(1) = should be 0. log*(4) = should be 2. but my method only print out zero and i couldn't figure out the problem.can some one help me?

public static int logCalculator(double n) {
    if (n == 1) {
        return 0;
    } else {
        return 1 + logCalculator(n * n);
    }
}

This will work for base 2 logs

public static int logCalculator1(double n) {
    if (n < 2)
       return 0;
    return 1 + logCalculator1(n / 2);
}

NOTE: this will round down always and with high numbers is inaccurate, in addition you can make it for all bases like this:

public static int logCalculator(int base, double n) {
        if (base > 0) {
            if (n < base) {
                return 0;
            } else {
                return 1 + logCalculator(base, (int)(n / base));
            }
        } return 0;
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM