3

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 ?

sophros
  • 14,672
  • 11
  • 46
  • 75
Marky Mark
  • 103
  • 2
  • 12

4 Answers4

2

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)
Abhijeetk431
  • 847
  • 1
  • 8
  • 18
  • Sorry for this. decrement will be outside if and print will be outside loop. I did not test before posting this answer. Editing the answer to one which should work. – Abhijeetk431 Aug 10 '17 at 06:23
1

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

from fractions import gcd
print(gcd(8, 22)) 
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
1

Either you can go with math library as suggested above otherwise the fastest way to calculate is

def gcd(m,n):
    if m<n: #assuming that m should always be greater than n
        (m,n) = (n,m)

    while m%n !=0:
        (m,n) = (n, m%n)
    return n

Hope this helps

HimanshuGahlot
  • 561
  • 4
  • 11
0

This works for me in Python3 :

 def highestFactor(numX,numY):
     print('in')
     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) 
  • Your code throws an error saying "wrong indent" on line with the decrementing statement. I moved the indentation to be at the same level as the while statement which I find reasonable and the program launches. I can see "in" being printed out but that's the end of it. – Marky Mark Aug 08 '17 at 13:17
  • @MarkyMark You should look if the indent of each line is correct. One Tab Indent have have 4 spaces in my programm like the code I posted. In python it is important that this indets are correct because we have no semicolon –  Aug 09 '17 at 06:05