[Tutor] why?

Chris Fuller cfuller at thinkingplanet.net
Thu May 29 04:25:20 CEST 2008


On Wednesday 28 May 2008 20:32, bob gailer wrote:
> Robert William Hanks wrote:
> >  Need ti find out whem a number o this form i**3+j**3+1 is acube.
> >  tryed a simple brute force code but, why this not work?
> >
> > def iscube(n):
> >     cubed_root = n**(1/3.0)
> >     if round(cubed_root)**3 == n:
> >         return True
> >     else:
> >         return False
> >
> > for i in range(1,10000000):
> >     for j in range(1,10000000):
> >          soma= i**3 +j**3 +1
> >          if isCube(soma):
> >              print i
> >              print j
> >              print soma
>
> Assuming you fixed the problem, do you know of any cases for which i**3
> +j**3 +1 is a cube?
>
> Also note this program will run for a LONG time.
>
> You can shorten the run time:
>
> for i in range(1,10000000):
>     for j in range(j,10000000): # test each combination once
>          soma =  i**3 +j**3 +1
>          cubed_root = soma**(0.333) # function call and division take
> extra time and there is no need for either
>          if abs(cubed_root  - round(cubed_root)) < .01: # this is a
> guess at close enough, and cheaper than cubing?
>              print i
>              print j
>              print soma

Actually, another flaw is the isCube (or iscube) function.  This will produce 
false cubes, due to the rounding and floating point approximations.

If you turn the problem around, and iterate through all n**3, and then iterate 
through all i,j less than n, and find all the i,j such that 
i**3+j**3+1==n**3, the run time will be much, much less for any given n, and 
eliminates the approximations.

Cheers



More information about the Tutor mailing list