在 使用这个 Python 脚本来模拟巴贝奇差分机 这篇文章中,Python 为巴贝奇提出的确定二维金字塔中弹珠数量的问题提供了一种替代解决方案。巴贝奇的 差分机 通过一个表格解决了这个问题,表格显示了弹珠的行数和弹珠的总数。
经过一番思考,查尔斯·巴贝奇 的幽灵回复说:“这一切都很好,但这里你只取行数并给出弹珠的数量。使用我的表格,我还可以告诉你,给定一定数量的弹珠,你可以构建多大的金字塔;只需在表格中查找即可。”
Python 不得不同意这确实是事实,但它知道肯定也可以解决这个问题。Python 稍作延迟,又拿出了另一个简短的脚本。这个解决方案涉及到反向思考数学。
MarbNum = (N * (N + 1))/2
我可以用以下公式开始求解
N * (N + 1) = MarbNum * 2
由此可以得到一个近似解
N = int(sqrt(MarbNum * 2))
但是,解决这个问题的整数 *N* 可能大一,所以我需要对此进行测试。换句话说,正确的行数将是 *N* 或 *N-1*。这是最终脚本
#!/usr/bin/env python
# babbage2.py
"""
Using Charles Babbage's conception of a marble-counting operation for a regular
pyramid of marbles, starting with one at the top with each successive row having
one more marble than the row above it.
Will give you the total number of rows possible for a pyramid, given a total number
of marbles available.
As a bonus, you also learn how many are left over.
"""
import math
MarbNum = input("Enter the number of marbles you have: ")
MarbNum = int(MarbNum)
firstguess = int(math.sqrt(MarbNum*2))
if (firstguess * (firstguess + 1) > MarbNum*2):
correctNum = firstguess - 1
else:
correctNum = firstguess
MarbRem = int(MarbNum - (correctNum * (correctNum + 1)/2))
# some grammatical fixes
if MarbRem == 0:
MarbRem = "no"
if MarbRem == 1:
marbleword = "marble"
else:
marbleword = "marbles"
print ("You can have",correctNum, "rows, with",MarbRem, marbleword, "remaining.")
输出将如下所示
Enter the number of marbles you have: 374865
You can have 865 rows, with 320 marbles remaining.
巴贝奇先生的幽灵印象深刻。“啊,你的 Python 引擎确实令人印象深刻!如果我有时间完成那个项目,它肯定可以与我的 分析机 相媲美。”
评论已关闭。