programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 1000 decimal digits? how do I count them?

Travis Gn
Greenhorn
Posts: 19
I just started using Java, I completed my homework assignment in VB, but now I want to do it in java.
Problem: What is the largest value of n for which 2 to the nth power has fewer than 100 decimal digits. Also, fewer than 1000 decimal digits?
I don't know how to tell the length of a string, or a double, or what ever type I should be using for this problem?
I also don't know how to raise a number to a power? I guess just using a loop and multplying it again and again? It seems there should be a better way, but I can't find it.
The more help the better, any code examples are greatly appriciated. I seem to learn best from them.

Gary Mann
Ranch Hand
Posts: 37
Check out the java.lang.Math class. It has a method for raising powers (pow) plus lots of other useful stuff.
I suspect your homework is a programming exercise rather than a Math problem, but I think there is a simple way to calculate this. It's a long time since I was at high school, but to determine "n", can't you just calc the log to base 2 of the target and take the integer part? e.g. log to base 2 of 100 is 6.629 so n = 6.
In Java, a method to do this would be:

This runs into trouble for very large numbers due to the size of a double. e.g. 1 followed by 1000 digits is too large. If the target is always a power of 10, then you could use:

Travis Gn
Greenhorn
Posts: 19
I took your advise about the math. I think that saved me lines of code and hours of headaches. Thank you. Since you were able to help with the math on that last one, I am working on another.
x^x = 10^100
and
x^x = 10^1000