Reputation: 2134
I am doing the following exercise: The number of digits of a power of 2.. The statement is:
What is 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
Then, given the exponent, what would be the number of digits of that power?
I have tried the following answer:
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;
}
}
However it times out with big exponents like: 562078812
How could we improve this solution? Is there any fastest answer?
I have also read:
Upvotes: 1
Views: 1059
Reputation: 4957
In decimal system, there will be exactly (n+1) digits in 10 power n.
The trick here is to find number of decimal digits in the exponent of '2'.
The difficult way to find the answer is to actually calculate 2 power n and then count the number of digits. However, this method requires huge computing power.
The simpler answer lies in the difference between 10 and 2.
If power of 2 raises by 1 in binary system, then digits in decimal system raise only by log 2 base 10!
For a raise of n powers in binary, the equivalent will be (n *log2_base_10 + 1) in decimal system.
Working solution:
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));
}
}
Output:
$ javac Power.java
$ java PowerNumber of digits in 2 power 50000000 = 15051501
Upvotes: 1
Reputation: 294
Use static method like below to compute number of digits. I think this is faster way
static int countDigits(int n)
{
return (int)(n * Math.log10(2) + 1);
}
Upvotes: 0
Reputation: 134
The fastest answer is to use math.
The number of digits in 2^n is (nlog₁₀2)+1 .
You can achieve that by simply returning n * Math.log10(2) + 1
. Good luck.
Upvotes: 3