简体   繁体   中英

Using a function that finds divisors, find the greatest common divisor of any two given two positive integers

This is what I have got till now

def div(x):
    A=[]
    for i in range(1,x):
        if x%i==0:
            A.append(i)
    print(A)
div(45)
div(50)
n=0
for i in range(1, min(45, 50)+1): 
    if 45%i==50%i==0: 
        n+=1
print(max(n))
TypeError                                 Traceback (most recent call last)
<ipython-input-8-80ad9173d3fa> in <module>
     11     if 45%i==50%i==0:
     12         n+=1
---> 13 print(max(n))

TypeError: 'int' object is not iterable

I have tried multiple logic but all end up with some error. This is the most appropriate one. I am still a newbie so a simple program is still creating problems for me. This problem was just taken to test our logic building.

Your line n=0 defines the name n as an integer. Then later you try to execute print(max(n)) .

In other words, you try to calculate the max() of a single integer. This is what raises your error message. The documentation for max() gives two valid uses of max() : a single iterable (such as a list) or multiple values (such as integers). A single integer is not allowed.

I'm not sure just what your intent was so I cannot recommend a small change to your program. I do recommend that you change your approach. Instead, you can do this:

  1. Call div() on each of your two integers, resulting in two lists of divisors.
  2. Convert each list to a Python set .
  3. Calculate the intersection of those two sets (see the previous link for the operation to do this). You now have a set of common divisors.
  4. Find the maximum value in that intersection set. Since a set is an iterable, max() will work on that set. The resulting maximum is your greatest common divisor.

The code should be easy for you to write. If you have difficulty, show your attempt and ask for more help.

By the way, your div function is not correct. The upper limit on the range should be x + 1 to include the number x as a divisor--any integer divides itself. And rather than printing the list, div() should return the list to the calling routine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM