How to solve diophantine problems?
John Machin
sjmachin at lexicon.net
Tue May 14 09:56:03 EDT 2002
"Joshua, Y.J. Lai" <g893404 at oz.nthu.edu.tw> wrote in message news:<abp8bb$vs$1 at thccy25.nthu.edu.tw>...
> Dear everyone:
>
> I can roughly solve the diophantine problem by using a nest loop
> ex.
[snip]
> But if I want to limit the maximum amount of balls (k) in this question
> then I will add an additional line:
> k=input("Please define the Max of balls: ")
> However, I do not know how to write the checking loops in this case?
> Because, the x and y are uncertain now. Could anyone please kindly help me.
> Thank you.
You probably want something like this. As Emile said, don't use
input().
import sys
def td(x):
"The number of balls used to construct a tetrahedron"
return x*(x+1)*(x+2)/6
def tri(y):
"The number of balls used to construct a triangle"
return y*(y+1)/2
def dio1(n):
# n is max # balls on one edge of tetrahedron or triangle
for x in xrange(n):
a=td(x)
for y in xrange(n):
b=tri(y)
if a==b!=0:
print "x = %d and y = %d , number = %d" % (x,y,a)
def dio2(k):
# k is max number of balls in total
for x in xrange(sys.maxint):
a=td(x)
if a >= k:
break
for y in xrange(sys.maxint):
b=tri(y)
if a + b > k:
break
if a==b!=0:
print "x = %d and y = %d , number = %d" % (x,y,a)
Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import diophant
>>> diophant.dio1(100)
x = 1 and y = 1 , number = 1
x = 3 and y = 4 , number = 10
x = 8 and y = 15 , number = 120
x = 20 and y = 55 , number = 1540
>>> diophant.dio2(500)
x = 1 and y = 1 , number = 1
x = 3 and y = 4 , number = 10
x = 8 and y = 15 , number = 120
>>> diophant.dio2(5000)
x = 1 and y = 1 , number = 1
x = 3 and y = 4 , number = 10
x = 8 and y = 15 , number = 120
x = 20 and y = 55 , number = 1540
>>> diophant.dio2(50000)
x = 1 and y = 1 , number = 1
x = 3 and y = 4 , number = 10
x = 8 and y = 15 , number = 120
x = 20 and y = 55 , number = 1540
x = 34 and y = 119 , number = 7140
>>>
Tighter conditions could be used in the two tests of when to break out
of the loop -- but you would have to solve a quadratic and a cubic.
HTH,
John
More information about the Python-list
mailing list