0

I've been working on a small program that takes the input of two numbers and gives the greatest common divisor. I have managed to get the program to at least print out all common divisors until the greatest number is reached, but all I need to print is the max value. Unfortunately, I can't get seem to get this to work. I've tried passing i though max() but was received an error that ''int' objects are not iterable''. Thus I am wondering if anyone could help me find a solution that will allow me to print only the max value as opposed to all values without having to employ much more complex coding methods. Here is the code

def great_divisor():
m = int(raw_input("Choose a number"))
n = int(raw_input("Choose another number"))
#lowest number assigned to d
if m > n:
    d = n
else:
    d = m

for i in range(1, d + 1):

    if (n%i == 0 and m%i == 0):
        print(max(i))
return
prance
  • 137
  • 1
  • 3
  • 12
  • 2
    `d = min(m,n)` should replace your `if...else`, for one thing. – Kyle Pittman Oct 08 '15 at 18:17
  • Why not just use `gcd` from the `fractions` module? Related [post](http://stackoverflow.com/questions/11175131/code-for-greatest-common-divisor-in-python). `gcd` is in the `math` module if you are using 3.3 – SirParselot Oct 08 '15 at 18:20
  • the point of the exercise isn't calculating gcd, but rather working with for loops. I would have if the point was to calculate that efficiently – prance Oct 08 '15 at 18:23

3 Answers3

1

The easiest way is to use range(d, 0, -1) and just return the first divisor you find. No need to use max.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0

Max can only be applied to an iterable, a list for example.

You can add all the common divisor in a list and get the max.

for i in range(1, d + 1):
    if (n%i == 0 and m%i == 0):
        divisors.append(i)
print(max(divisors))
mat__
  • 3
  • 3
0

How about this?

maxn = 0
for i in range(1, d + 1):

    if (n%i == 0 and m%i == 0):
        maxn = i

return maxn
jcfollower
  • 3,103
  • 19
  • 25