0
####
# GCD calculator using euclidean algorithm
####

def euclid_gcd(x,y) :
    new_gcd = y
    remainder = x % y
    print x,y, new_gcd, remainder
    if(remainder != 0) :
        euclid_gcd(y,remainder)   
    else :
        print x,y, new_gcd, remainder
        return new_gcd

print 'x | y | new_gcd | remainder'
print euclid_gcd(252,198)

However, when I run this code it returns this...

x | y | new_gcd | remainder
252 198 198 54
198 54 54 36
54 36 36 18
36 18 18 0
36 18 18 0
None

It should return 18 in this case yet it returns none where did I go wrong everything seems to be following the logical steps??

2 Answers 2

4

You should do return euclid_gcd(y,remainder).

You forgot to return the recursion result here:

if(remainder != 0) :
    euclid_gcd(y,remainder)   
Sign up to request clarification or add additional context in comments.

5 Comments

Oh yea? where should I place that please?
Oh wow that fixed it! could I bother you for one more second and ask why that fixed it?
@cat: Most compiled languages wouldn't let you get away (as in won't compile) with returning something in one part, but not another. The same thing applies here - you have to return the value you get back from the method call, or it won't give you back an answer.
@cat, I believe Makoto has described this better than I can :)
Brilliant I can't believe I didn't notice that thank you guys!
1

Another way to solve your problem

def euclid_gcd(x, y):
    new_gcd = y
    remainder = x % y
    print x, y, new_gcd, remainder
    if remainder != 0:
        new_gcd = euclid_gcd(y, remainder)   
    print x, y, new_gcd, remainder
    return new_gcd

I suggested this because it seems strange otherwise to have the variable new_gcd if you only ever initialise it to y

The reason that you were getting None is because Python implicitly returns None if the function doesn't explicitly return anything

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.