How to solve diophantine problems?

Christopher Browne cbbrowne at acm.org
Sat May 18 17:47:15 EDT 2002


Centuries ago, Nostradamus foresaw when "Joshua, Y.J. Lai" <g893404 at oz.nthu.edu.tw> would write:
> I can roughly solve the diophantine problem by using a nest loop
> ex.
> 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
>
> for x in xrange(100):
>     for y in xrange(100):
>         a=td(x)
>         b=tri(y)
>         if a==b!=0:
>             print "x = %d and y = %d , number = %d" % (x,y,a)

> 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.

I'd suggest a _completely_ different structuring of the nested loop.
You can make the program on the order of 100 times as fast by simply
storing the td() and tri() values in dictionaries, and comparing
dictionaries, thus:

A={}
B={}
maxballs = 25000
# Compute the function values, ONCE
for x in xrange(1200):
    ba=td(x)
    if (ba < maxballs):
        A[ba] = x    # Only keep number of balls if it's legal
    bb=tri(x)
    if (bb < maxballs):
        B[bb] = x

# Now, search A for all the numbers of balls
for k in A.keys():
    if B.has_key(k):   # If there's a match in B, show it...
        print "A Balls:", k, "A count:", A[k], "B Balls:", 
               k, "B count:", B[k]

... which runs lickety-split ...

A Balls: 10 A count: 3 B Balls: 10 B count: 4
A Balls: 120 A count: 8 B Balls: 120 B count: 15
A Balls: 7140 A count: 34 B Balls: 7140 B count: 119
A Balls: 1540 A count: 20 B Balls: 1540 B count: 55
A Balls: 1 A count: 1 B Balls: 1 B count: 1
A Balls: 0 A count: 0 B Balls: 0 B count: 0
-- 
(reverse (concatenate 'string "gro.mca@" "enworbbc"))
http://www.cbbrowne.com/info/linuxdistributions.html
"It has every known bug fix to everything." -- KLH (out of context)



More information about the Python-list mailing list