Zuter_242
Zuter_242

Reputation: 103

Variable changes between end of previous loop and start of next?

Here's my full code for Project Euler #66, tested for #64 (note that the variable that causes the problem, num, isn't an indexing variable in the while loop so the cause isn't immediately obvious):

from math import gcd, sqrt

for D in range(23,1001):
    h=(1,int(sqrt(D))); k=(0,1)
    num,denom=(1,sqrt(D)-int(sqrt(D)))

    while not h[1]**2-D*k[1]**2==1:
        print()
        print('before',round(num),round(denom-sqrt(D)))
        tgcd=gcd(round(num),round(2*sqrt(D)*denom-denom**2))
        print('gcd',tgcd)
        num*=((2*sqrt(D)-denom)/tgcd)
        denom*=((2*sqrt(D)-denom)/tgcd)
        print('after filling',round(num-sqrt(D)),round(denom))
        coeff=0
        while num>denom:
            num-=denom
            coeff+=1
        print('after coefficient extracted',round(num-sqrt(D)),round(denom))
        num,denom=denom,num
        print('coeff',coeff)
        h=(h[1],coeff*h[1]+h[0])
        k=(k[1],coeff*k[1]+k[0])
        print('after everything',round(num),round(denom-sqrt(D)),'<-The first number isn not carried over into the next loop here' if round(num)==7 else '')

And here's the output (it also breaks for the next iteration of the while loop, however it's fine for all previous iterations):


before 1 -4
gcd 1
after filling 4 7
after coefficient extracted -3 7
coeff 1
after everything 7 -3 

before 7 -3
gcd 7
after filling 3 2
after coefficient extracted -3 2
coeff 3
after everything 2 -3 

before 2 -3
gcd 2
after filling 3 7
after coefficient extracted -4 7
coeff 1
after everything 7 -4 <-The first number is not carried over into the next loop here

before 1 -4
gcd 1
after filling 4 8
after coefficient extracted -4 8
coeff 1
after everything 8 -4 

before 1 -5
gcd 1
after filling 5 0

Upvotes: 0

Views: 77

Answers (1)

jeekiii
jeekiii

Reputation: 296

The outer loops runs again and this piece of code:

num,denom=(1,sqrt(D)-int(sqrt(D)))

assigns 1 back to the num variable.

You can see it if you add a print or a debug breakpoint in the outer loop, it gets executed.

Oftentimes when something truly crazy happens it's good to put into question assumptions we made when debugging.

Upvotes: 1

Related Questions