Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the greatest common factor with Python

I'm trying to determine the greatest common factor of two numbers in Python. This is what I've got. It makes sense to me, not so much to Python though. I'm not getting any specific error from Python. It just won't run.

def highestFactor(numX,numY):
    if numX > numY:
        x = numY
    else:
        x = numX
    while x > 1:
        if numX % x == 0 and numY % x == 0:
        print x
        break

    x -= 1

highestFactor(8,22)

Any thoughts ?

like image 443
Marky Mark Avatar asked Jun 06 '26 16:06

Marky Mark


2 Answers

You are decreasing the value of x outside the loop.

Try this:-

def highestFactor(numX,numY):
    if numX > numY:
        x = numY
    else:
        x = numX
    while x > 1:
        if numX % x == 0 and numY % x == 0:
            break
        x -= 1
    print x



highestFactor(8,22)
like image 151
Abhijeetk431 Avatar answered Jun 09 '26 05:06

Abhijeetk431


you have a bad indentation on x-=1, anyway there is a gcd function in python...

from fractions import gcd
print(gcd(8, 22)) 
like image 44
Yoav Glazner Avatar answered Jun 09 '26 05:06

Yoav Glazner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!