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
3
  • 2
    d = min(m,n) should replace your if...else, for one thing. Commented Oct 8, 2015 at 18:17
  • Why not just use gcd from the fractions module? Related post. gcd is in the math module if you are using 3.3 Commented Oct 8, 2015 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 Commented Oct 8, 2015 at 18:23

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks that managed to reverse the numbers, now just to figure out how to get it to only return one divisor
Just do if (n%i == 0 and m%i == 0): return i
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

1 Comment

hmm, not working. Now the program just returns none as opposed to a number
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))

3 Comments

Alternatively, you can declare a max_divisor variable and chek if i is greater than max_divisor.
did you mean .add or .append? I had to use append to get the same effect. I'm running 2.7 though...
Yes sorry, it is .append()

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.