代码之家  ›  专栏  ›  技术社区  ›  Enoy

得到2次幂的位数,大指数?

  •  0
  • Enoy  · 技术社区  · 5 年前

    The number of digits of a power of 2. . 声明如下:

    2 ---> 1 digit 
    2 * 2 = 4 ---> 1 digit 
    2 * 2 * 2 = 8 ---> 1 digit
      2 * 2 * 2 * 2 = 16 ---> 2 digits
      ... ... ... 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 1024 ---> 4 digits
    

    那么,给定指数,那么 那力量?

    我试过以下答案:

    import java.math.BigInteger; 
    public class Power {
        public static long digit(long exp) {
        System.out.println("exp: "+exp);
        BigInteger pow = BigInteger.valueOf(2).pow((int)exp);
        return String.valueOf(pow).split("").length;
        }
    }  
    

    但是它的大指数是:562078812

    我也读过:

    2 回复  |  直到 5 年前
        1
  •  1
  •   Amir    5 年前

    最快的答案是用数学。 2^n中的位数是(nlog2)+1。 n * Math.log10(2) + 1 . 祝你好运。

        2
  •  1
  •   Gopinath    5 年前

    在十进制中,10次方n中正好有(n+1)个数字。

    • 10幂2有3位数。
    • 10幂3有4位数。
    • .....
    • 10幂n有(n+1)个数字。

    这里的诀窍是找出 指数中的数字 2个 '.

    找到答案的困难方法是实际计算 2功率n 然后数数数字。然而,这种方法需要巨大的计算能力。

    更简单的答案是10和2之间的差异。

    对于二进制中n次幂的增加,等价于 (n*log2_base_10+1)十进制。

    public class Power {
        public static long digit(long exp) {
            return (long) (Math.ceil(exp * Math.log10(2)) + 1);
        }
    
        public static void main(String[] args) {
            long exp = 50000000;
            System.out.println("Number of digits in 2 power " + exp 
                                + " = " + Power.digit(50000000));
        }
    }
    

    输出:

    $javac Power.java版本

    二次幂位数50000000=15051501

        3
  •  0
  •   Omid    5 年前

    使用如下静态方法计算位数。我觉得这样比较快

    static int countDigits(int n) 
    { 
        return (int)(n * Math.log10(2) + 1); 
    }