0

Hi I'm participating in a math competition and there is this question " N = 9+99+999+... (a number that has 999 nines), how many are there 1 in N. So I did the question mathematically and it said that there are 998 ones in N (and that is the correct answer) but when I made a python program to solve this question:

N = 0
nr_of_ones = 0
for i in range(1, 1000):
    N += 10**i - 1
length_N = len(str(N))
N = str(N)
print("N =", N)
print("Length of N =", length_N)
for x in range(length_N):
    if N[x] == 1:
        nr_of_ones += 1

print(nr_of_ones)

but the result that i got was false, it said that the length of N = 1000 and the nr_of_ones = 999 (wich is false). If anyone could help me correct my code I would be very grateful.

I've tried to rewrite it countless times, to use the package math, and to use golang but none of it worked, it should display that the number of ones = 998 but it says it's 999

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    Does this answer your question? [Handling very large numbers in Python](https://stackoverflow.com/questions/538551/handling-very-large-numbers-in-python) – Stephen C Mar 12 '23 at 11:23
  • What version of Python are you using? – Stephen C Mar 12 '23 at 11:23
  • 1
    The program is basically correct (although `N[x] == 1` should be `N[x] == '1'`). There are 999 ones in the sum, maybe take another look at your maths result. – motto Mar 12 '23 at 11:32
  • plugging the question in wolfram alpha also yields 999 (though I counted the ones by hand as I couldn't find a popcnt and wolfram didn't want to give me the result as text) – Masklinn Mar 12 '23 at 11:33

1 Answers1

2

Note: just an illustration rather than a rigorous proof.

                                `n` 9s
  9    +  99   +  999   + ... + 99..9

                                `n` 0s
= 10-1 + 100-1 + 1000-1 + ... + 100..0-1

                    `n` 0s
= 10 + 100 + 1000 + 100..0  -  n

  `n` 1s
= 1...1110 - n

  `n-3` 1s
= 1...10000 + 1110 - n

For `n=999`, 1110 - n = 111

 `999-3` 1s    `3` 1s
= 1...10000  +  111

So the total number of 1s is 999-3+3, i.e. 999. Rejoice, your programme works :-)

motto
  • 2,888
  • 2
  • 2
  • 14