PYTHON CODE The figure on the left is an example of “triangular” numbers, the fi
ID: 3684860 • Letter: P
Question
PYTHON CODE
The figure on the left is an example of “triangular” numbers, the figure on the right an example of “square” numbers. Each figure adds a gnomon, another layer, to the figure based on the shape of the figure. For each figure, the first gnomon is indicated by the green ball, the second by the red balls, the third by the yellow balls and the fourth gnomon by the blue balls. The actual triangular and square numbers are the sum of the balls in the respective figure. That is, you take the sum of all the balls in each gnomon up to the last layer you added, and that is the number. For example, the left figure represents the triangular number 10, and the right figure represents the square number 16. Below is a table of the triangular and square numbers.
A particularly interesting relationship is that any square number can be written as the sum of two triangular numbers. For example, 9 = 6 + 3. We are going to use that relationship in this assignment.
Program Specifications So the problem is this. It is kind of a puzzle that, once solved, should end up as a rather small program.
1. Ask the user for a square number (a number which has an integer square root).
2. If the number provided is not a square, report an error and end the program.
3. If the number is a square, then find the two triangular numbers that sum to the square number (remember: there is a proof that every square number is the sum of two triangular numbers).
4. Print out the two triangular numbers and the original square number. What are the two triangular numbers which, when added together, give a square number? That’s the puzzle. Once you figure out the puzzle, the program is quite short.
Explanation / Answer
square = [1,4,9,16,25,36,49,64,81,100]
traingle = [1,3,6,10,15,21,28,36,45,55]
x = input("enter a number: ")
flag=0
for index in range(len(square)):
if( x == square[index] )
flag=1
if( flag = 0)
print "input is not a square!"
exit()
for index1 in range(len(square)):
for index2 in range(len(square)):
sum = traingle[index1] + triangle[index2]
if(x == sum)
print " %d is sum of %d and %d" %(x,triangle[index1],triangle[index1])
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.