英文:
Python doesnt handle well big numbers
问题
"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 (which 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 math package, and to use Golang, but none of it worked. It should display that the number of ones = 998, but it says it's 999."
英文:
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
答案1
得分: 2
请注意,这只是一个示例,而不是一个严格的证明。
`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
对于 `n=999`,1110 - n = 111
`999-3` 1s `3` 1s
= 1...10000 + 111
因此,1的总数是 999-3+3
,即 999
。
庆幸,您的程序正常运行
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论