BreakingExpress

This Python script mimics Babbage’s Difference Engine

In Use this Python script to simulate Babbage’s Difference Engine, Python provided another answer to Babbage’s downside of figuring out the variety of marbles in a two-dimensional pyramid. Babbage’s Difference Engine solved this utilizing a desk displaying the variety of marble rows and the whole variety of marbles.

After some contemplation, Charles Babbage‘s ghost replied, “This is all well and good, but here you only take the number of rows and give the number of marbles. With my table, I can also tell you how large a pyramid you might construct given a certain number of marbles; simply look it up in the table.”

Python needed to agree that this was certainly the case, but it knew that certainly this should be solvable as effectively. With little delay, Python got here again with one other quick script. The answer entails considering by the maths in reverse.

MarbNum = (N * (N + 1))/2

Which I can start to resolve with:

N * (N + 1) = MarbNum * 2

From which an approximate answer is perhaps:

N = int(sqrt(MarbNum * 2))

But the integer N that solves this is perhaps too massive by one, so I would like to check for this. In different phrases, the right variety of rows will both be N or N-1. Here is the ultimate script:

#!/usr/bin/env python
# babbage2.py
"""
Using Charles Babbage's conception of a marble-counting operation for an everyday
pyramid of marbles, beginning with one on the prime with every successive row having
yet another marble than the row above it.
Will provide the complete variety of rows attainable for a pyramid, given a complete quantity
of marbles accessible.
As a bonus, you additionally study what number of are left over.
"""

import math

MarbNum = enter("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 == zero:
    MarbRem = "no"
 
if MarbRem == 1:
    marbleword = "marble"
else:
    marbleword = "marbles"
   
print ("You can have",correctNum, "rows, with",MarbRem, marbleword, "remaining.")

The output will look one thing like this:

Enter the variety of marbles you might have:  374865
You can have 865 rows, with 320 marbles remaining.

And Mr. Babbage’s ghost was impressed. “Ah, your Python Engine is spectacular certainly! Surely it’d rival my Analytical Engine, had I had the time to finish that undertaking.”

Exit mobile version