2
$\begingroup$

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

  • 0
    Yes, the formula would be much less efficient than the method you give.2012-04-17

2 Answers 2

6

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.

  • 0
    @AsafKaragila: -)2012-04-17
4

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.