# Is there a formula that will take me from a “given number of digits” to “largest possible integer”?

Apologies for what may be a simple question, but I don't have a background in mathematics beyond high school.

I'm trying to work out a formula, that when given a number, say 2, to treat this as "number of digits" and calculate the largest possible integer.

For example :

• If 2, then largest number possible is 99
• If 3, then largest number possible is 999
• If 4, then largest number possible is 9999

My quick and dirty solution (programmers hat on here), is to just count upwards from 0 to the given number, appending 9, and returning the result, however there must be a mathematical formula that can do this in a cleaner and more efficient manner.

Thanks

-
Formula we can give, but it might not be more efficient as you expect... – Aryabhata Apr 17 '12 at 20:40
Yes, the formula would be much less efficient than the method you give. – Graphth Apr 17 '12 at 20:42

In base $10$, the number you want is $10^n - 1$.

If you are passing strings around, your method will be fast enough.

If you are passing ints around, you can compute it using the above, but might have to worry about overflows etc. Of course, computing $10^n$ might be slower than just appending nines to your string...

So codewise it might be cleaner, but it need not be more efficient and might open up the overflow can of worms.

-
Actually not just in base 10... In any base that uses "10" to signify the least number of two digits. – Asaf Karagila Apr 17 '12 at 20:37
@AsafKaragila: Right! Reminds me of the joke: There are 10 kinds of people. Those who know binary and those who don't :-) – Aryabhata Apr 17 '12 at 20:39
Actually there are 10 kinds of people: Those who know ternary numbers and those who don't. :-) (I think there must be infinitely many variations on this joke!) – Asaf Karagila Apr 17 '12 at 20:43
@AsafKaragila: -) – Aryabhata Apr 17 '12 at 20:45

Given $k$ how about $10^k-1$?

This number has only $9$'s and exactly $k$ digits. I suppose that this is what you meant. Note that this is not limited to decimal digits, you can do that in any base as long as "$10$" is the smallest number of two digits.

-